Reputation: 1394
I have class with such properties:
public DateTime Start { get; set; }
public DateTime Finish { get; set; }
And such ViewModel:
<StackPanel>
<DatePicker SelectedDate="{Binding Start}" />
<DatePicker SelectedDate="{Binding Finish}" />
</StackPanel>
I want to enable validation. So, when Start > Finish there must be error. What is the simplest way to provide such validation?
Upvotes: 1
Views: 2148
Reputation: 1394
Well, I've found answer myself) I extended my TimeRange class to implement IDataErrorInfo interface like this:
public class TimeRange : IDataErrorInfo
{
public DateTime Start { get; set; }
public DateTime Finish { get; set; }
#region IDataErrorInfo Members
public string Error
{
get { throw new NotImplementedException(); }
}
private bool _IsValid()
{
return Finish > Start;
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Start" && !_IsValid())
result = "Start must occure before Finish!";
else if (columnName == "Finish" && !_IsValid())
result = "Finish must occure after Start!";
return result;
}
}
#endregion
}
And then change my xaml code to:
<DatePicker SelectedDate="{Binding Start, UpdateSourceTrigger=LostFocus,
ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
<DatePicker SelectedDate="{Binding Finish, UpdateSourceTrigger=LostFocus,
ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
Upvotes: 4