Data Annotations, IDataErrorInfo and MVVM

只愿长相守 提交于 2019-12-02 13:40:24

To keep validation running, IDataErrorInfo must be implemented by the data context, which property is bound to the control. So, it should be something like:

public class PersonViewModel : IDataErrorInfo 
{
    [Required(AllowEmptyStrings = false)]
    public string Name
    {
        get
        {
             return _person.Name
        }
        set
        {
             _person.Name = value;
        }
    }    

    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            return OnValidate(propertyName);
        }
    }

    protected virtual string OnValidate(string propertyName)
    {
        /* ... */
    }
}

There's no need to implement IDataErrorInfo in model, this is view model's responsibility. Usually, IDataErrorInfo is implemented by the base class for your view models.

By the way, why OnValidate is protected? How do you imagine overriding of this method?

Keep your definition in XAML notifyonvalidation error and validatesondata errors set to true. And in VM use simple Viewmodel which has validation on setter function for desired properties, if validation fails it should throw validation error and xaml will know that it is invalid.

public class PersonViewModel
{
    private Person _person;

    public string Name
    {
        get
        {
            return _person.Name
        }
        set
        {
            if(value == string.empty)
               throw new ValidationException("Name cannot be empty");
            _person.Name = value;
        }
    }
}

Now you will need to handle this in xaml and display error text from exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!