C# INotifyCollectionChanged未更新UI
我有一个如下所示的类。为了简洁起见,我删除了所有函数C# INotifyCollectionChanged未更新UI,c#,wpf,inotifycollectionchanged,C#,Wpf,Inotifycollectionchanged,我有一个如下所示的类。为了简洁起见,我删除了所有函数 public class PersonCollection:IList<Person> {} 我的UI如下所示 DataContextClass contextclass = new DataContextClass(); this.DataContext = new DataContextClass(); <ListBox Margin="5,39,308,113" ItemsSource="
public class PersonCollection:IList<Person>
{}
我的UI如下所示
DataContextClass contextclass = new DataContextClass();
this.DataContext = new DataContextClass();
<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" />
单击按钮时,我的列表框未使用新值更新。这里我缺少什么。
INotifyCollectionChanged
必须由集合类实现。不是由包含集合的类创建的。您需要从
DataContextClass
中删除INotifyPropertyChanged
,并将其添加到PersonCollection
中,而不是使用IList
使用ObservableCollection
并定义PersonCollection
类,如下所示:
public class PersonCollection : ObservableCollection<Person>
{}
以下是更多帮助您在WPF中使用ObservableCollection类的文章:
非常感谢您的回答,但我有一个疑问,如果我不想改变我的人员集合,我如何通过在DataContextClass@Vikram:你不能。WPF引擎在绑定到
ItemsSource
的属性上查找该接口。它不会在数据上下文中寻找接口。谢谢你的回答。但不幸的是,我将无法在PersonCollection中进行更改。
public class PersonCollection : ObservableCollection<Person>
{}
public class ObservableCollection<T> : Collection<T>,
INotifyCollectionChanged, INotifyPropertyChanged