根据一个属性验证两个属性的推荐方法是什么?
典型的例子是开始日期应该低于结束日期:
。
ReactiveValidatedObject在这里有什么帮助呢?
我最好需要一个在WPF和Silverlight中工作的解决方案。
发布于 2011-05-26 15:48:22
如果您正在使用MVVM模式的WPF应用程序,它将是相当直接的。而不是由视图执行验证,而是由ViewModel来完成。视图应该只是一个哑巴层,显示ViewModel公开的内容。所有的UI验证都应该由ViewModel完成,这样它们才是可测试的。
我的ViewModel可能是这样的:
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;
}
}然后对这个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>https://stackoverflow.com/questions/5896027
复制相似问题