IDataErrorInfo:如何知道所有属性是否有效? [英] IDataErrorInfo : How to know if all properties are valid?

查看:62
本文介绍了IDataErrorInfo:如何知道所有属性是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF应用程序(.Net 3.5),该应用程序使用ViewModel上的IDataErrorInfo来验证输入.

I have a WPF application(.Net 3.5) which uses the IDataErrorInfo on the ViewModel to validate input.

效果很好,用户控件获得了正确的UI反馈.

It works great, the usercontrol get the correct UI feedback.

问题在于用户仍然可以更改所选元素或保存该元素.

The problem is that the user can still change the selected element, or save this element.

所以我的问题是:我怎么知道我所有的属性都是有效的?或至少我所有显示的值均有效.目的是在此结果上绑定一些IsActive

So my question is: How can I know that all my properties are valid? Or at least that all my displayed values are valid. The goal is to bind some IsActive on this result

推荐答案

从您对IDataErrorInfo实现的评论中,将您的实现更改为这种样式....

From your comment on your implementation of IDataErrorInfo change your implementation to this style....

#region IDataErrorInfo Members

public string Error
{
    get { return this[null] }
}

public string this[string columnName]
{
    get
    {
        StringBuilder result = new StringBuilder();
        if (string.IsNullOrEmpty(columnName) || columnName == "FirstName")
        {
            if (string.IsNullOrEmpty(FirstName))
                result.Append("Please enter a First Name\n");
        }
        if (string.IsNullOrEmpty(columnName) || columnName == "LastName")
        {
            if (string.IsNullOrEmpty(LastName))
                result.Append("Please enter a Last Name\n");
        }
       if (string.IsNullOrEmpty(columnName) || columnName == "Age")
        {
            if (Age < = 0 || Age >= 99)
                result.Append("Please enter a valid age\n");
        }
        return (result.Length==0) ? null : result.Remove(result.Length-1,1).ToString();
    }
}

#endregion


public bool IsValid {
   get { return string.IsNullOrEmpty(this.Error); }
}

然后在您的财产变更事件中

Then in your property changed event

if (e.PropertyName == "Error") {
   OnPropertyChanged(this,new PropertyChangedEventArgs("IsValid"));
}
if (e.PropertyName != "Error" && e.PropertyName != "IsValid") {
   OnPropertyChanged(this,new PropertyChangedEventArgs("Error"));
}

这篇关于IDataErrorInfo:如何知道所有属性是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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