tôi đã không tìm thấy một cách dễ dàng để làm điều đó. Tôi tìm thấy một số mã xung quanh các bẫy để recurse thông qua tất cả các điều khiển trên biểu mẫu và xác định xem có ai trong số họ có lỗi xác nhận. Tôi đã kết thúc biến nó thành một phương pháp khuyến nông:
// Validate all dependency objects in a window
internal static IList<ValidationError> GetErrors(this DependencyObject node)
{
// Check if dependency object was passed
if (node != null)
{
// Check if dependency object is valid.
// NOTE: Validation.GetHasError works for controls that have validation rules attached
bool isValid = !Validation.GetHasError(node);
if (!isValid)
{
// If the dependency object is invalid, and it can receive the focus,
// set the focus
if (node is IInputElement) Keyboard.Focus((IInputElement)node);
return Validation.GetErrors(node);
}
}
// If this dependency object is valid, check all child dependency objects
foreach (object subnode in LogicalTreeHelper.GetChildren(node))
{
if (subnode is DependencyObject)
{
// If a child dependency object is invalid, return false immediately,
// otherwise keep checking
var errors = GetErrors((DependencyObject)subnode);
if (errors.Count > 0) return errors;
}
}
// All dependency objects are valid
return new ValidationError[0];
}
Vì vậy, sau đó khi người dùng nhấp chuột vào nút Save trên một hình thức, tôi làm điều này:
var errors = this.GetErrors();
if (errors.Count > 0)
{
MessageBox.Show(errors[0].ErrorContent.ToString());
return;
}
Nó làm việc nhiều hơn nó phải được nhưng sử dụng phương pháp mở rộng sẽ đơn giản hóa nó một chút.
Nguồn
2009-03-13 02:51:07
Đây là giải pháp tốt đẹp. Cảm ơn bạn. – Jirapong