最近的做个功能,当界面内textbox校验异常时,按钮不可用,网上关于WPF数据校验的文章很多,此处就不在介绍,关于如何捕获校验异常的文章却很多少,本文将介绍如何获取当前页面内产生的校验异常。
1.获取控件异常
这一步其实很简单,Validation提供了一个静态方法,可以直接获取控件是否有验证错误。
System.Windows.Controls.Validation.GetHasError(child)
2.获取页面内所需所有子控件的异常
此处我写了一个扩展方法,obj可以是UserControl也可以是Window,typename是要获取异常的控件类型
public static bool GetChildIsError(this DependencyObject obj, Type typename)
{
DependencyObject child = null;
bool isError = false;
try
{
for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if ((child.GetType() == typename))
{
if (System.Windows.Controls.Validation.GetHasError(child))
{
return true;
}
}
if (GetChildIsError(child, typename))
{
return true;
}
}
}
catch (Exception)
{
return false; ;
}
return isError;
}
3.MVVM中实现校验验证
3.1ViewModel中添加属性CurrentDependencyObject,CurrentDependencyObject binding当前界面或者控件。
private DependencyObject currentDependencyObject=new DependencyObject();
public DependencyObject CurrentDependencyObject
{
get { return currentDependencyObject; }
set { currentDependencyObject=value; }
}
3.2在实现ICommand接口的Command类中的CanExecute方法中验证。
protected bool CheckCanExecuteSave()
{
return !this.CurrentDependencyObject.GetChildIsError(typeof(System.Windows.Controls.TextBox));
}