Data Annotations, IDataErrorInfo and MVVM

前端 未结 2 1158
我寻月下人不归
我寻月下人不归 2021-01-26 05:29

I\'m trying to find the best way to validate data in MVVM. Currently, I\'m trying to use IDataErrorInfo with Data Annotations using the MVVM pattern.

However, nothing se

2条回答
  •  野的像风
    2021-01-26 06:05

    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

提交回复
热议问题