问题在Validation类中,我试图验证用户是否未选择任何日期。但是每次Date-picker控件每次在DateTime类型的变量(即开始时间,结束时间等)中发送选定的日期时,我都会使用INOtifyPropertyChanged和IDataErrorInfo进行验证。 这是DatePIcker控件的WPF代码
<DatePicker Name="dpStartDate" Height="30" Width="Auto">
<DatePicker.DisplayDate>
<Binding Path="startdate"
ValidatesOnDataErrors="True"
UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
<Binding.ValidationRules>
<!-- Checks for exceptions during the setting of the source property.
Alternatively, set ValidatesOnExceptions to True on the Binding.-->
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</DatePicker.DisplayDate>
</DatePicker>
下面的代码是用于验证的Model类 类TimingViewModel:INotifyPropertyChanged,IDataErrorInfo { 公共事件PropertyChangedEventHandler PropertyChanged =委托{};
private DateTime _startdate { get; set; }
private DateTime _enddate { get; set; }
private DateTime _starttime { get; set; }
private DateTime _endtime { get; set; }
private string _intervaltime { get; set; }
public bool ValidationEnabled { get; set; }
public DateTime startdate
{
get
{
return _startdate;
}
set
{
this._startdate = value;
PropertyChanged(this, new PropertyChangedEventArgs("startdate"));
}
}
public DateTime enddate
{
get
{
return _enddate;
}
set
{
this._enddate = value;
PropertyChanged(this, new PropertyChangedEventArgs("enddate"));
}
}
public DateTime starttime
{
get
{
return _starttime;
}
set
{
this._starttime = value;
PropertyChanged(this, new PropertyChangedEventArgs("starttime"));
}
}
public DateTime endtime
{
get
{
return _endtime;
}
set
{
this._endtime = value;
PropertyChanged(this, new PropertyChangedEventArgs("endtime"));
}
}
public string intervaltime
{
get
{
return _intervaltime;
}
set
{
this._intervaltime = value;
PropertyChanged(this, new PropertyChangedEventArgs("intervaltime"));
}
}
public string Error
{
get { return null; }
}
public string this[string propName]
{
get
{
string result = string.Empty;
if (ValidationEnabled)
{
if (propName == "startdate")
{
if (startdate.ToShortDateString() == null)
{
result = "StartDate is required.";
}
}
else if (propName == "enddate")
{
if (enddate.Date == null || startdate.Date > enddate.Date)
{
result = "End Date must not be less than start date";
}
}
else if (propName == "starttime")
{
if (starttime.TimeOfDay == null)
{
result = "Start Time Must Not be Empty";
}
}
else if (propName == "endtime")
{
if (starttime.TimeOfDay > endtime.TimeOfDay || endtime.TimeOfDay == null)
{
result = "End Time Must not be Empty";
}
}
else if (propName == "intervaltime")
{
if (string.IsNullOrEmpty(this.intervaltime))
{
result = "Interval Time must not be Empty";
}
}
}
return result;
}
}
}
在后面的代码中,我检查了这样的验证。但不会产生错误
if (Validation.GetHasError(dpStartDate) || Validation.GetHasError(dpEndDate) || Validation.GetHasError(cbStarttime)
|| Validation.GetHasError(cbEndtime) || Validation.GetHasError(cbIntervalTime))
{
return;
}