Data validation on ShowDialog window in WPF
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 开发者_如何学JAVAcheck 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
You CanExecute should look like this.
public bool CanExecuteOK
{
get
{
if (DataModelToValidate.Error == null && DataModelToValidate.Errors.Count == 0) return true;
else return false;
}
}
Here Error and Errors properties are nothing but Wrapper over this[string propertyName] (implemented implicitly for IDataErrorInfo).
Here is Sample Model Class:
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;
}
精彩评论