我有以下课程,我已经实现了IDataErrorInfo
接口,但它没有工作,即它没有进行验证。代码似乎很完美。我不知道为什么。我提出了一个断点,它甚至没有进入IDataErrorInfo Members
区域。
产品类
[DataContract()]
public class Product : IDataErrorInfo
{
[DataMember()]
public string Name{get;set;}
[DataMember()]
public string Code{get;set;}
#region IDataErrorInfo Members
public string Error
{
get
{
return null;
}
}
public string this[string property]
{
get
{
switch (property)
{
case "Name":
if (string.IsNullOrEmpty(Name))
return "Name is required";
break;
case "Code":
if (string.IsNullOrEmpty(Code))
return "Code is required";
break;
default:
break;
}
return null;
}
}
#endregion
public Product(string name, string code)
{
Name = name;
Code = code;
}
}
绑定textbox
<TextBox Grid.Column="1"
HorizontalAlignment="Left"
Height="23"
Margin="24,9,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="148" x:Name="txtName"
Text="{Binding Name,Mode=TwoWay,ValidatesOnDataErrors=True}"
MaxLength="50"/>
答案 0 :(得分:2)
您需要使用INotifyPropertyChanged
和IDataErrorInfo
使对象可观察,以便绑定知道属性已更改,并在ValidatesOnDataErrors=True
时检查是否存在任何错误
public class Product : IDataErrorInfo, INotifyPropertyChanged {
string _name;
[DataMember()]
public string Name{
get { return _name; }
set {
_name = value;
NotifyPropertyChanged("Name");
}
}
//...Other code removed for brevity
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
您甚至可以将属性更改的功能移到基类中以便重复使用
public abstract class PropertyChangedBase: INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
并像
一样使用它public class Product : PropertyChangedBase, IDataErrorInfo {
//Code removed for brevity
}