先介绍这个IDataErrorInfo接口,定义如下:
namespace System.ComponentModel
{
/// <summary>Provides the functionality to offer custom error information that a user interface can bind to.</summary>
[System.Reflection.DefaultMemberAttribute("Item")]
public interface IDataErrorInfo
{
/// <summary>Gets an error message indicating what is wrong with this object.</summary>
/// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
string Error { get; }
string this[string columnName] { get; }
}
}
{
/// <summary>Provides the functionality to offer custom error information that a user interface can bind to.</summary>
[System.Reflection.DefaultMemberAttribute("Item")]
public interface IDataErrorInfo
{
/// <summary>Gets an error message indicating what is wrong with this object.</summary>
/// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
string Error { get; }
string this[string columnName] { get; }
}
}
很早以前就在载体中实现了 IDataErrorInfo ,但一直有个头大的问题,也没有时间细看,就是我修改了对象的错误信息,如何让外界知道我的这个列的错误信息改变了。
今天有时间看看。NET的实现,原来他是触发了这个属性(字段)的值改变事件,也就是他认为是数据发生了改变,于是自己加入代码很容易实现了,但要记得在ClearErrors也触发一下。
public void SetError(string columnName,string errorInfo)
{
if (columnName == null || columnName.Equals(string.Empty))
_rowError = errorInfo;
else
{
Errors[columnName] = errorInfo;
OnPropertyChanged(new PropertyChangedEventArgs(columnName));//触发事件以便通知界面改变显示
}
}
{
if (columnName == null || columnName.Equals(string.Empty))
_rowError = errorInfo;
else
{
Errors[columnName] = errorInfo;
OnPropertyChanged(new PropertyChangedEventArgs(columnName));//触发事件以便通知界面改变显示
}
}
如果你实现了这个接口,你的载体绑定到界面时,你也可以像DataRow一样,在检查数据不正确时,调用SetError设置错误信息,使用系统默认的错误提示控件就可以显示自动显示错误了。