Validate depending properties in WPF and SL
What is the recommended approach for validating two properties depending one on the other?
Classical example is start should be lower than end date:
- user enters start "6th"
- user enters end "3rd" - both fields should be marked as invalid
- user corrects start to "1st" - both fields should b开发者_StackOverflowe ok
How can ReactiveValidatedObject help here?
I preferably need a solution which works in WPF and Silverlight.
If you are using MVVM pattern for WPF app, it will be pretty straight forward. Instead of the View doing the validation, the ViewModel will do it. View should just be a dumb layer displaying whatever the ViewModel exposes. All UI validation should be done by ViewModel so that they are testable.
My ViewModel may look like this:
class MyViewModel : INotifyPropertyChanged
{
/* declare ProperChanged event and implement OnPropertyChanged() method */
private DateTime _firstDate;
public DateTime FirstDate
{
get { return _firstDate; }
set
{
if (!AreDatesValid(value, _secondDate))
{
ErrorMessage = "Incorrect First Date";
return;
}
_firstDate = value;
OnPropertyChanged("FirstDate");
}
}
private DateTime _secondDate;
public DateTime SecondDate
{
get { return _secondDate; }
set
{
if (!AreDatesValid(_firstDate, value))
{
ErrorMessage = "Incorrect Second Date";
return;
}
_secondDate = value;
OnPropertyChanged("SecondDate");
}
}
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set
{
_errorMessage = value;
OnPropertyChanged("ErrorMessage");
}
}
private bool AreDatesValid(DateTime firstDate, DateTime secondDate)
{
if(firstDate <= secondDate )
return true;
return false;
}
}
And then databind View to this ViewModel ->
<DataTemplate DataType="{x:Type ViewModel:MyViewModel}">
<Grid>
<TextBox Text="{Binding Path=FirstDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding Path=SecondDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{Binding Path=ErrorMessage}" />
</Grid>
<DataTemplate>
精彩评论