当我重新实例 ObservableCollection 时会发生什么
我有一个 ObservableCollection
属性,还有这个属性
public ListCollectionView ListView
{
get
{
return (ListCollectionView)(CollectionViewSource.GetDefaultView(List));
}
}
,其中List是WPF中的ObservableCollection
,我有一个绑定到ListView属性的ListView控件。
因此,据我了解,如果我更改代码中的 ObservableCollection,它应该反映在视图中。
但是,如果我只是执行 List = new ObservableCollection
视图中的列表根本不会更新。如果我正在执行 MVVM 操作,是否有办法让它在代码后面刷新?
I have a ObservableCollection
property and also this property
public ListCollectionView ListView
{
get
{
return (ListCollectionView)(CollectionViewSource.GetDefaultView(List));
}
}
With List being the ObservableCollection
In WPF I have a ListView Control bound to the ListView property.
So as I understand it if I change the ObservableCollection in code it should be reflected in the View.
But what if I just do List = new ObservableCollection<SomeType>(someElements)
The list in the View doesn't update at all. Is there anyway to get it to refresh in code behind if I'm doing it MVVM ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为视图添加另一个更改通知:
Add another change notification for the view:
您应该引发
ListView
的PropertyChanged
事件。You should raise the
PropertyChanged
event forListView
.在这种情况下,您必须实现
INotifyPropertyChanged
并为ListView
属性触发PropertyChanged
事件,以强制框架更新绑定。不过,通常情况下,您希望避免重新实例化,并始终更新相同的ObservableCollection
。In that case you would have to implement
INotifyPropertyChanged
and fire thePropertyChanged
event for theListView
property to force the framework to update the binding. Generally, however, you want to avoid re-instancing, and always update the sameObservableCollection
.您需要为列表本身引发属性更改事件,要么将该属性设为 DependancyProperty 要么使用 INotifyPropertyChanged
you need to raise a property changed event for the List itself, either make the property a DependancyProperty or use INotifyPropertyChanged
该控件绑定到
ListView
属性并侦听IPropertyChanged
事件,以便在基础视图发生更改时它可以自行更新。但是,当您更改基础集合时,它无法神奇地确定视图已更改。直接的解决方案是在更改
List
的值后立即触发ListView
属性的PropertyChanged
。The control binds to the
ListView
property and listens to theIPropertyChanged
event so that it can update itself if the underlying view changes. However, it cannot magically determine that the view has changed when you changed the underlying collection.A direct solution would be to trigger
PropertyChanged
for theListView
property just after you change the value ofList
.