我上课有这样的属性:
public DateTime Start { get; set; }
public DateTime Finish { get; set; }
这样的ViewModel:
<StackPanel>
<DatePicker SelectedDate="{Binding Start}" />
<DatePicker SelectedDate="{Binding Finish}" />
</StackPanel>
我想启用验证。所以,当开始&gt;完成必须有错误。提供此类验证的最简单方法是什么?
答案 0 :(得分:3)
好吧,我自己找到了答案)我扩展了我的TimeRange类来实现IDataErrorInfo接口,如下所示:
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
}
然后将我的xaml代码更改为:
<DatePicker SelectedDate="{Binding Start, UpdateSourceTrigger=LostFocus,
ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
<DatePicker SelectedDate="{Binding Finish, UpdateSourceTrigger=LostFocus,
ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
答案 1 :(得分:2)
您可以使用Binding.ValidationRules
。
您可以找到MSDN示例here。
答案 2 :(得分:-2)
比较get的值。如果开始&gt;完成返回null或其他内容。