尽管在WPF中调用了GetErrors方法,但INotifyDataErrorInfo验证不起作用

时间:2018-09-20 08:20:07

标签: c# wpf validation

我有一个ValidatableObject类,该类实现了INotifyDataErrorInfo和INotifyPropertyChanged接口。

有趣的是,当我在viewmodel中创建ValidatableModel的新实例并在加载视图后调用Validate方法时。但是,当我在viewmodel的构造函数中创建我的模型并在加载视图后调用Validate方法时不起作用。

在加载视图之前和加载视图之后创建实例之间有什么区别?这是一些代码,我简化了

public class MyViewModel : ViewModelBase
    {
        private MyModel _myModel;
        public MyModel MyModel
        {
            get { return _myModel; }
            set
            {
                SetProperty(ref _myModel, value);
            }
        }

        public MyViewModel()
        {
            MyModel = new MyModel();
        }

        //this not working, I calls this after view loaded 
        public void Validate()
        {
            MyModel.Validate();
        }

        //this  working,  I calls this after view loaded 
        public void Validate()
        {
            MyModel = new MyModel();
            MyModel.Validate();
        }
    }

   [JsonObject]
    public partial class MyModel : ValidatableObject
    {
        private string _id;
        public string id
        {
            get { return _id; }
            set { SetProperty(ref _id, value); }
        }

        private string _status;
        [Required(AllowEmptyStrings = false, ErrorMessage = "Field is mandatory")]
        public string status
        {
            get { return _status; }
            set { SetProperty(ref _status, value); }
        }

        private string _requestId;
        public string requestId
        {
            get { return _requestId; }
            set { SetProperty(ref _requestId, value); }
        }
    }


                                <TextBox Width="135"
                                         Margin="10,0,0,0"
                                         Validation.ErrorTemplate="{StaticResource MyErrorTemplate}"
                                         Text="{Binding MyModel.status,NotifyOnTargetUpdated=True,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnDataErrors=True}" />

0 个答案:

没有答案