我想创建自己的数据验证系统,比如说
List<ValidationRule> list = new List<ValidationRule>();
list.Add(new ValidationRule(sometext, "Method regexTextValidation"));
list.Add(new ValidationRule(phonenumeber, "Method regexPhoneValidation"));
list.Add(new ValidationRule(somedate, "Method regexDateValidation"));
我想存储每个方法的结果并循环遍历它们,以便查看是否有错误,如果是有问题的话。
修改:
sometext是一个字符串,regexTextValidation是一个方法,我正在尝试一些东西,我想我会使用字典Dictionary<int, Tuple<string, bool>> _DicValidationRules;
我会这样称呼它_DicValidationRules.Add(1, new Tuple<string, bool>("some text", regexTextValidation("some text")));
答案 0 :(得分:2)
这不是你在WPF中使用验证规则的方式。您通常在XAML中引用它们并为绑定定义它们。这是一个例子......
<DataGridTextColumn Header="Value" EditingElementStyle="{StaticResource errorStyle}">
<DataGridTextColumn.Binding>
<Binding Path="Value" NotifyOnValidationError="False" >
<Binding.ValidationRules>
<local:NumberValidationRule ValidationStep="RawProposedValue"/>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
此特定验证规则验证用户是否在文本字段中键入了大于0的数字。您可以拥有多个验证规则,它们都必须返回真实的验证结果,否则会显示错误。
public class NumberValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
double v = 0.0;
if(double.TryParse(value as string, out v))
{
if(v <= 0.0)
{
return new ValidationResult(false, "number must be greater than 0");
}
}
else
{
return new ValidationResult(false, "entered value is not a number");
}
return new ValidationResult(true, null);
}
}