在WPF验证两个属性 [英] Validating two properties in WPF

查看:107
本文介绍了在WPF验证两个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种属性的类:

    public DateTime Start { get; set; }
    public DateTime Finish { get; set; }

和这样的视图模型:

    <StackPanel>
        <DatePicker SelectedDate="{Binding Start}" />
        <DatePicker SelectedDate="{Binding Finish}" />
    </StackPanel>



我想启用验证。所以,当开始>完成,必须有错误。什么是提供这样的验证最简单的方法?

I want to enable validation. So, when Start > Finish there must be error. What is the simplest way to provide such validation?

推荐答案

好吧,我已经找到答案我自己)我伸出我的TIMERANGE类来实现这样的IDataErrorInfo的接口:

Well, I've found answer myself) I extended my TimeRange class to implement IDataErrorInfo interface like this:

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代码:

And then change my xaml code to:

        <DatePicker SelectedDate="{Binding Start, UpdateSourceTrigger=LostFocus, 
            ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
        <DatePicker SelectedDate="{Binding Finish, UpdateSourceTrigger=LostFocus,
            ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />

这篇关于在WPF验证两个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆