我有一个如下所示的类。为简洁起见,我删除了所有函数
public class PersonCollection:IList<Person>
{}现在我又多了一个Model类,如下所示。AddValueCommand是从ICommand派生的类,我再一次省略它。
public class DataContextClass:INotifyCollectionChanged
{
private PersonCollection personCollection = PersonCollection.GetInstance();
public IList<Person> ListOfPerson
{
get
{
return personCollection;
}
}
public void AddPerson(Person person)
{
personCollection.Add(person);
OnCollectionChanged(NotifyCollectionChangedAction.Reset);
}
public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { };
public void OnCollectionChanged(NotifyCollectionChangedAction action)
{
if (CollectionChanged != null)
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));
}
}
ICommand addValueCommand;
public ICommand AddValueCommand
{
get
{
if (addValueCommand == null)
{
addValueCommand = new AddValueCommand(p => this.AddPerson(new Person { Name = "Ashish"}));
}
return addValueCommand;
}
}
}在主窗口中,我将UI绑定到Model,如下所示
DataContextClass contextclass = new DataContextClass();
this.DataContext = new DataContextClass();我的UI如下所示
<ListBox Margin="5,39,308,113" ItemsSource="{Binding Path=ListOfPerson}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Height="20" Text="{Binding Path=Name}"></TextBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Button" HorizontalAlignment="Left" Command="{Binding Path=AddValueCommand}" Margin="233,39,0,73" />单击按钮时,我的列表框不会更新为新值。我在这里错过了什么。
发布于 2013-04-30 18:47:02
INotifyCollectionChanged必须由集合类实现。而不是通过包含该集合的类。
您需要从DataContextClass中删除INotifyPropertyChanged并将其添加到PersonCollection中。
发布于 2013-04-30 18:50:08
不使用IList,而是使用ObservableCollection<T>并定义PersonCollection类,如下所示:
public class PersonCollection : ObservableCollection<Person>
{}您可以阅读有关ObservableCollection<T>类here的更多信息,该类是专门为WPF DataBinding场景中的集合更改通知而设计的。
从下面的MSDN中的定义可以看出,它已经实现了INotifyCollectionChanged
public class ObservableCollection<T> : Collection<T>,
INotifyCollectionChanged, INotifyPropertyChanged下面是更多帮助你在WPF中使用ObservableCollection类的文章:
Create and Bind to an ObservableCollection
An introduction to ObservableCollection in Wpf
https://stackoverflow.com/questions/16297983
复制相似问题