我在 WPF 4.5 项目中对 INotifyDataErrorInfo 做了一个简单的实现。这是 WPF 的一个新界面,但在 Silverlight 中已经有一段时间了。
我知道 NET4.5 仍然被认为是 alpha,但我正在尝试确定它是我的代码还是框架有问题。
该接口按预期工作,但在对象绑定到 DataGrid 时失败。
我收到的例外是:
System.NullReferenceException 未被用户代码处理
Message=Object 引用未设置为对象的实例。
Source=PresentationFramework StackTrace: 在 MS.Internal.Data.ClrBindingWorker.OnDataErrorsChanged(INotifyDataErrorInfo indei, String propName) 在 MS.Internal.Data.PropertyPathWorker.OnErrorsChanged(Object sender, DataErrorsChangedEventArgs e) 在 System.Windows.WeakEventManager.ListenerList`1。 DeliverEvent(Object sender, EventArgs e, Type managerType) at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args) at System.ComponentModel.ErrorsChangedEventManager.OnErrorsChanged(Object sender, DataErrorsChangedEventArgs args) at INotifyDataErrorInfoTest.Person.NotifyErrorsChanged(String property ) 在 INotifyDataErrorInfoTest\Person.cs:第 109 行,位于 INotifyDataErrorInfoTest\Person 中的 INotifyDataErrorInfoTest.Person.AddErrorForProperty(String property, String error)。cs:INotifyDataErrorInfoTest.Person.Validate(String propertyName) 中 INotifyDataErrorInfoTest\Person.cs 的第 122 行:INotifyDataErrorInfoTest.Person.set_FirstName(String value) 中 INotifyDataErrorInfoTest\Person.cs 的第 150 行:第 18 行
代码位于http://dl.dropbox.com/u/14740106/INotifyDataErrorInfoTest.zip的下方或项目中
如果一致认为这是一个错误,那么我将发布到 MS Connect。
测试:有两个文本框绑定到 Person 对象的单个实例。将第一个文本框的值设置为 James,它将验证失败并显示红色框。如果您将网格中任何用户的名字设置为 James,则会引发异常。
PS:我知道这不是 MVVM,但这只是为了证明或反驳问题。
public class Person : INotifyDataErrorInfo, INotifyPropertyChanged
{
string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
Validate("FirstName");
OnPropertyChanged("FirstName");
}
}
string _lastName;
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
Validate("LastName");
OnPropertyChanged("LastName");
}
}
public Person()
{
}
public Person(string first, string last)
{
this._firstName = first;
this._lastName = last;
}
#region INotifyPropertyChanged Members
/// <summary>
/// Event to indicate that a property has changed.
/// </summary>
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Called when a property is changed
/// </summary>
/// <param name="propertyName">The name of the property that has changed.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Called when a property is changed
/// </summary>
/// <param name="e">PropertyChangedEventArgs</param>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
//Validate the property
Validate(e.PropertyName);
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
#endregion
#region INotifyDataErrorInfo Members
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
return (_errors.Values);
}
MakeOrCreatePropertyErrorList(propertyName);
return _errors[propertyName];
}
public bool HasErrors
{
get
{
return (_errors.Where(c => c.Value.Count > 0).Count() > 0);
}
}
void NotifyErrorsChanged(string property)
{
if (ErrorsChanged != null)
{
ErrorsChanged(this, new DataErrorsChangedEventArgs(property));
}
}
public void ClearErrorFromProperty(string property)
{
MakeOrCreatePropertyErrorList(property);
_errors[property].Clear();
NotifyErrorsChanged(property);
}
public void AddErrorForProperty(string property, string error)
{
MakeOrCreatePropertyErrorList(property);
_errors[property].Add(error);
NotifyErrorsChanged(property);
}
void MakeOrCreatePropertyErrorList(string propertyName)
{
if (!_errors.ContainsKey(propertyName))
{
_errors[propertyName] = new List<string>();
}
}
#endregion
/// <summary>
/// Force the object to validate itself using the assigned business rules.
/// </summary>
/// <param name="propertyName">Name of the property to validate.</param>
public void Validate(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
return;
}
if (propertyName == "FirstName")
{
if (FirstName == "James")
{
AddErrorForProperty(propertyName, "FirstName can't be James");
}
else
{
ClearErrorFromProperty(propertyName);
}
}
}
}
public class NameList : ObservableCollection<Person>
{
public NameList()
: base()
{
Add(new Person("Willa", "Cather"));
Add(new Person("Isak", "Dinesen"));
Add(new Person("Victor", "Hugo"));
Add(new Person("Jules", "Verne"));
}
}
public partial class MainWindow : Window
{
Person _person = new Person();
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public Person Person
{
get { return _person; }
}
}
<Window x:Class="INotifyDataErrorInfoTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:INotifyDataErrorInfoTest"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<c:NameList x:Key="NameListData"/>
</Window.Resources>
<StackPanel>
<StackPanel.Resources>
<Style TargetType="TextBox">
<Setter Property="Margin" Value="5"></Setter>
</Style>
</StackPanel.Resources>
<TextBox Text="{Binding Person.FirstName, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}"/>
<TextBox Text="{Binding Person.LastName, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}"/>
<TextBlock>To generate an error, set the FirstName of any row to James.
</TextBlock>
<DataGrid ItemsSource="{Binding Source={StaticResource NameListData}}" AutoGenerateColumns="True"></DataGrid>
</StackPanel>
</Window>