Reputation: 5660
What is the recommended approach for validating two properties depending one on the other?
Classical example is start should be lower than end date:
How can ReactiveValidatedObject help here?
I preferably need a solution which works in WPF and Silverlight.
Upvotes: 1
Views: 327
Reputation: 3139
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>
Upvotes: 2