public class CountValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
double d = 0.0;
if (double.TryParse((string)value, out d) )
{
return new ValidationResult(true, "OK");
}
else
{
return new ValidationResult(false, "无法解析输入");
}
}
}
引入规则
<UserControl.Resources>
<ResourceDictionary>
<converter:CountValidationRule x:Key="CountValidationRule"/>
</ResourceDictionary>
</UserControl.Resources>
使用规则
<TextBox hc:InfoElement.Title="纬度: " >
<TextBox.Text>
<Binding Path="StationInfo.Latitude">
<Binding.ValidationRules>
<converter:CountValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
如果需要校验界面是否包含未解决的报错可以获取页面所有的报错信息
public bool AreAllValidationsSucceeded(DependencyObject dependencyObject)
{
bool allValidationsSucceeded = true;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, i);
if (child is FrameworkElement)
{
FrameworkElement frameworkElement = child as FrameworkElement;
// 检查绑定错误
if (Validation.GetHasError(frameworkElement))
{
allValidationsSucceeded = false;
break; // 一旦发现有错误,就不再遍历
}
}
// 递归遍历子元素
if (!AreAllValidationsSucceeded(child))
{
allValidationsSucceeded = false;
break;
}
}
return allValidationsSucceeded;
}
调用
bool allValidationsSucceeded = AreAllValidationsSucceeded(this);
if (!allValidationsSucceeded)
{
return;
}
//TODO
标签:ValidationRule,return,校验,allValidationsSucceeded,bool,child,false,wpf,dependency
From: https://www.cnblogs.com/ives/p/18357635