は、私はそれを行うための簡単な方法を発見していません。トラップの周りにいくつかのコードがあり、フォーム上のすべてのコントロールを再帰的に調べ、検証エラーがあるかどうかを判断します。私は、拡張メソッドにそれを回すことになった:
// 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];
}
それでは、ユーザーがフォーム上の[保存]ボタンをクリックしたときに、私はこれを行う:
var errors = this.GetErrors();
if (errors.Count > 0)
{
MessageBox.Show(errors[0].ErrorContent.ToString());
return;
}
それはそれがあるべきよりも多くの仕事です拡張メソッドを使用すると、それが少し単純化されます。
これは良い解決策です。ありがとうございました。 – Jirapong