2013-03-04 126 views
3

在我目前的项目中,我必须处理WPF表单中的数据验证。我的表单位于ResourceDictionnary的DataTemplate中。我可以保存和加载我的表单中的数据,这要归功于两个按钮,它们对数据进行序列化和反序列化(通过两个DelegateCommand)。WPF验证错误

如果我的表单的一个字段为空或无效,保存按钮将被禁用。由于UpdateSourceTrigger属性,每次更改字段时都会检查它。这就是为什么我需要在我的C#代码中知道一个字段是否无效以更新我的保存命令。

目前,我在我的XAML绑定中使用了ExceptionValidationRule,我不知道这是否是一个很好的实践。我无法实现ValidationRule,因为我需要在C#代码中知道字段是否无效,以更新保存命令(启用或禁用保存按钮)。

<TextBox> 
    <Binding Path="Contact.FirstName" UpdateSourceTrigger="PropertyChanged"> 
     <Binding.ValidationRules> 
      <ExceptionValidationRule/> 
     </Binding.ValidationRules> 
    </Binding> 
</TextBox> 

在这个blog,我们可以看到:

在二传手提高例外是不是一个很好的方法,因为这些属性也可以通过代码设定,有时它是确定暂时离开他们错误值。

我已经阅读了这个post但我不能使用它,我的TextBox在DataTemplate中,我不能在我的C#代码中使用它们。

所以,我不知道是否应该更改我的数据验证,并且不要使用ExceptionValidationRule。

+0

你尝试IDataErrorInfo的和MVVM? – blindmeis 2013-03-04 10:41:00

+0

是的,我已经使用MVVM。 IDataErrorInfo似乎是一个很好的解决方案...它会比ExceptionValidationRule更好吗? – Max 2013-03-04 10:56:33

+1

我会说是的,但它也有它的缺点。特别是如果您的vw中的属性的类型不是字符串。我们在我们的项目中使用idataerrorinfo并且它可以工作 – blindmeis 2013-03-04 11:42:38

回答

5

谢谢blindmeis,你的想法很好。 IDataErrorInfo似乎比ExceptionValidationException更好,它的工作原理。

以下为符合我的项目,它的例子: IDataErrorInfo sample

它不使用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; 
     } 
    } 

} 

在XAML代码,不要忘了更改绑定:

<TextBox> 
    <Binding Path="Contact.Name" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" NotifyOnValidationError="True"/> 
</TextBox>