Interface IDataErrorInfo 不起作用

本文关键字:不起作用 IDataErrorInfo Interface | 更新日期: 2023-09-27 18:32:12

我有以下类,我已经实现了IDataErrorInfo接口,但它不起作用,即它不进行验证。代码似乎很完美。我不知道为什么。我放了一个断点,它甚至没有进入IDataErrorInfo Members区域。

产品类别

[DataContract()]
public class Product : IDataErrorInfo
{
    [DataMember()]
    public string Name{get;set;}
    [DataMember()]
    public string Code{get;set;}
    #region IDataErrorInfo Members
    public string Error
    {
        get
        {
            return null;
        }
    }
    public string this[string property]
    {
        get
        {
            switch (property)
            {
                case "Name":
                    if (string.IsNullOrEmpty(Name))
                        return "Name is required";
                    break;
                case "Code":
                    if (string.IsNullOrEmpty(Code))
                        return "Code is required";
                    break;
                default:
                    break;
            }
            return null;
        }
    }
    #endregion
    public Product(string name, string code)
    {
        Name = name;
        Code = code;
    }
 }

用于绑定textbox的 XAML

<TextBox Grid.Column="1" 
                         HorizontalAlignment="Left" 
                         Height="23" 
                         Margin="24,9,0,0" 
                         TextWrapping="Wrap" 
                         VerticalAlignment="Top" 
                         Width="148" x:Name="txtName" 
                         Text="{Binding Name,Mode=TwoWay,ValidatesOnDataErrors=True}" 
                         MaxLength="50"/>

Interface IDataErrorInfo 不起作用

您需要使用 INotifyPropertyChangedIDataErrorInfo使对象可观察,以便绑定知道属性已更改,并在ValidatesOnDataErrors=True时检查是否有任何错误

public class Product : IDataErrorInfo, INotifyPropertyChanged {
    string _name;
    [DataMember()]
    public string Name{
        get { return _name; }
        set {
            _name = value;
            NotifyPropertyChanged("Name");
        }
    }
    //...Other code removed for brevity
    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(string propertyName) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

您甚至可以将属性更改的功能移出到基类中以便重用,如下所示

public abstract class PropertyChangedBase: INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(string propertyName) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

并像使用它一样使用

public class Product : PropertyChangedBase, IDataErrorInfo {
    //Code removed for brevity
}