Max*_*Max 4 data-binding validation wpf validationrule
在我目前的项目中,我必须以WPF形式处理数据验证.我的表单位于ResourceDictionnary中的DataTemplate中.我可以通过两个按钮来保存和加载表单中的数据,这两个按钮序列化和反序列化数据(通过两个DelegateCommand).
如果我的表单中的一个字段为空或无效,则禁用保存按钮.由于UpdateSourceTrigger属性,每次更改时都会检查一个字段.这就是为什么我需要在C#代码中知道如果字段无效以更新我的保存命令.
目前,我在我的XAML绑定中使用ExceptionValidationRule,我想知道它是否是一个很好的实践.我无法实现ValidationRule,因为我需要在C#代码中知道字段是否无效,以更新保存命令(启用或禁用保存按钮).
<TextBox>
<Binding Path="Contact.FirstName" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
在这篇博客中,我们可以阅读:
在Setter中引发异常并不是一个很好的方法,因为这些属性也是由代码设置的,有时可以暂时保留它们的错误值.
我已经阅读过这篇文章,但我不能使用它,我的TextBox在DataTemplate中,我不能在我的C#代码中使用它们.
所以,我想知道我是否应该更改我的数据验证并且不要使用ExceptionValidationRule.
谢谢blindmeis,你的想法是好的.IDataErrorInfo似乎比ExceptionValidationException更好,它可以工作.
这是一个与我的项目匹配的示例: IDataErrorInfo示例
它不使用DelegateCommand,但很容易修改.您的模型必须实现IDataErrorInfo:
public class Contact : IDataErrorInfo
{
public string Error
{
get { throw new NotImplementedException(); }
}
public string Name { get; set; }
public string this[string property]
{
get
{
string result = null;
if (property== "Name")
{
if (string.IsNullOrEmpty(Name) || Name.Length < 3)
result = "Please enter a Name";
}
return result;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在XAML代码中,不要忘记更改绑定:
<TextBox>
<Binding Path="Contact.Name" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" NotifyOnValidationError="True"/>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5112 次 |
| 最近记录: |