问题
Suppose I have two DatePicker
, I want that the first DatePicker
date must be less to the second DatePicker
. The date of the second DatePicker
must be greather then the first.
If the first DatePicker
have a date greather than the second, then a validation error should appear on the datepicker.
These are my DatePickers
:
<DatePicker x:Name="StartPeriod"
SelectedDate="{Binding PeriodStartDate}">
</DatePicker>
<DatePicker x:Name="EndPeriod"
SelectedDate="{Binding PeriodEndDate}">
</DatePicker>
回答1:
Implement the INotifyDataErrorInfo
interface in your view model:
public class ViewModel : INotifyDataErrorInfo
{
private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();
private DateTime _periodStartDate;
public DateTime PeriodStartDate
{
get { return _periodStartDate; }
set { _periodStartDate = value; Validate(); }
}
private DateTime _periodEndDate;
public DateTime PeriodEndDate
{
get { return _periodEndDate; }
set { _periodEndDate = value; Validate(); }
}
private void Validate()
{
if (_periodStartDate > _periodEndDate)
_validationErrors.Add(nameof(PeriodStartDate), $"{nameof(PeriodEndDate)} cannot be smaller than {nameof(PeriodStartDate)}");
else
_validationErrors.Clear();
RaiseErrorsChanged(nameof(PeriodStartDate));
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private void RaiseErrorsChanged(string propertyName) =>
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
public bool HasErrors => _validationErrors.Count > 0;
public IEnumerable GetErrors(string propertyName)
{
string error;
if (_validationErrors.TryGetValue(propertyName, out error))
return new string[1] { error };
return null;
}
}
Please refer to this article for more information.
来源:https://stackoverflow.com/questions/52006436/how-to-use-a-validation-between-two-datepicker