How to use a validation between two datepicker?

谁说我不能喝 提交于 2019-12-11 15:18:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!