WPF MVVM对虚拟机上直通属性的验证



我试图在WPF+MVVM中使用IDataErrorInfo进行验证。我按照MSDN的文章介绍了如何实现它。问题是我该如何处理VM上的pass through属性?

例如,

public class A : INotifyPropertyChanged, IDataErrorInfo
{
    protected string _Name;
    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }
    public string this[string propertyName]
    {
        get
        {
            string result = null;
            if (propertyName == "Name")
            {
                if (Name == "ABC")
                {
                    result = "Name cannot be ABC";
                }
            }
            return result;
        }
    }
}
public class ViewModel : INotifyPropertyChanged
{
    A a = new A();
    public string ModelName
    {
        get
        {
            return a.Name;
        }
        set
        {
            a.Name = value;
            OnNameChanged();
            OnPropertyChanged("ModelName");
        }
    }
}    
<TextBox Name="txtName" Text="{Binding Path=ModelName, ValidatesOnDataErrors=True}" />

我必须在视图模型上做些什么,这样我就不必在视图模型上再次验证Name属性了?

谢谢

您需要的是通过ViewModel公开整个class A。

这篇博文(不是完美的,但是)展示了一个简单的方法:http://www.eidias.com/Blog/2012/7/2/simple-validation-in-wpf-mvvm-using-idataerrorinfo

你也有一个有趣的讨论如何显示这个主题上的错误:MVVM模式,IDataErrorInfo和绑定显示错误?

验证发生在具有绑定集的类上。在你的例子中,它是ViewModel。如果你需要直通属性那就把IDataErrorInfo加到ViewModel上让它也直通

//视图模型

public string this[string propertyName]
{
    get
    {
        if (propertyName == "ModelName")
        {
            return a["Name"];
        }
        return null;
    }
}

我不知道在您的情况下ViewModel上没有IDataErrorInfo的方法

最新更新