0

I have a window that I display as ShowDialog in the window I have some textboxes binding to object that implement INotifyPropertyChannges and IDataErrorInfo. I want that the OK button will enabled just if all thextboxes validted and I want that just if the user click on OK buton the next move will occur.

I can bind the button to ICommand and check the textboxes valitation in CanExcute() but then what can I do in the Excute? the object dont know about the window. I can also check the textboxes valitation and then raise event that all valid and enable the OK button but then there will be dupliacte code because I checked already in the IDataErrorInfo implmention.

So what is the right way?

Thanks in advance

4

1 回答 1

0

你可以执行应该是这样的。

   public bool CanExecuteOK        
   {
        get
        {
              if (DataModelToValidate.Error == null && DataModelToValidate.Errors.Count == 0) return true;
              else return false;
        }
   }

这里的 Error 和 Errors 属性只不过是 this[string propertyName] 上的 Wrapper(为 IDataErrorInfo 隐式实现)。

这是示例模型类:

    public class SampleModel: IDataErrorInfo, INotifyPropertyChanged
    {
        public SampleModel()
        {
            this.Errors = new System.Collections.ObjectModel.ObservableCollection<string>();
        }
        private string _SomeProperty = string.Empty;
        public string SomeProperty
        {
            get
            {
                return _SomeProperty;

            }
            set
            {
                if (value != _SomeProperty)
                {
                    _SomeProperty= value;
                    RaisePropertyChanged("SomeProperty");
                }
            }
        }
....
....
        //this keeps track of all errors in current data model object
        public System.Collections.ObjectModel.ObservableCollection<string> Errors { get; private set; }
        //Implicit for IDataErrorInfo
        public string Error
        {
            get
            {
                return this[string.Empty];
            }
        }

        public string this[string propertyName]
        {
            get
            {

                string result = string.Empty;
                propertyName = propertyName ?? string.Empty;

                if (propertyName == string.Empty || propertyName == "SomeProperty")
                {
                    if (string.IsNullOrEmpty(this.SomeProperty))
                    {
                        result = "SomeProperty cannot be blank";
                        if (!this.Errors.Contains(result)) this.Errors.Add(result);
                    }
                    else
                    {
                        if (this.Errors.Contains("SomeProperty cannot be blank")) this.Errors.Remove("SomeProperty cannot be blank");
                    }
                }
......
      return result;
    }
于 2011-07-12T02:08:06.163 回答