验证WPF中的两个属性
本文关键字:两个 属性 WPF 验证 | 更新日期: 2023-09-27 18:16:36
我有这样一个类:
public DateTime Start { get; set; }
public DateTime Finish { get; set; }
和ViewModel:
<StackPanel>
<DatePicker SelectedDate="{Binding Start}" />
<DatePicker SelectedDate="{Binding Finish}" />
</StackPanel>
我想启用验证。当Start> Finish时,肯定会有错误。提供这种验证的最简单方法是什么?
嗯,我自己找到了答案)我扩展了我的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}" />
您可以使用Binding.ValidationRules
。
您可以在这里找到MSDN示例
比较get上的值。如果Start>Finish返回null之类的