为什么更改 ObservableCollection 但不替换它时会发生 UpdateSourceTrigger?
我刚刚开始使用 WPF,并试图了解数据绑定。
在我的项目中,我有一个绑定到属性的列表框,该属性从 DependancyProperty 获取/设置。
如果我这个属性是一个 ObservableCollection (并且我将 UpdateSourceTrigger 设置为 PropertyChanged),我的列表框会正确表示集合的内容并随之更新。 然而,当我将整个集合换成新集合时,它不再更新。
这是为什么呢?列表框是否永久绑定到该特定对象? Set 访问器中的 SetValue() 是否应该不会导致它绑定到新访问器并进行相应更新?
I am just starting out with WPF and am trying to understand data binding.
In my project I have a listbox bound to a property, which gets/sets from a DependancyProperty.
If I this property is an ObservableCollection (and I set UpdateSourceTrigger to PropertyChanged) my listbox correctly represents the content of the collection and updates with it.
When I swap out the collection entirely for a new one though, it no longer updates.
Why is this? Does the listbox become bound to that specific object permanently? Should SetValue() in the Set accessor not cause it to bind to the new one, and update accordingly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
UpdateSourceTrigger 仅在源因控件中的更改而更新时影响。它与您对对象本身所做的操作无关。
我强烈建议您不要覆盖对集合的引用,因为任何还需要集合的
CollectionChanged
事件的事件处理程序都需要重新连接。我不确定如果您绑定到依赖项属性,如何处理通知,但如果您更改源并且它不是 DP,您需要通知绑定。这可以通过实现 INotifyPropertyChanged 来完成。
例如
编辑:测试交换存储在DP中的集合,对我来说它按预期工作并且列表得到更新,显示新集合。
UpdateSourceTrigger only affects when the source is updated from changes in the control. It has nothing to do with what you do with the object on its own.
I greatly discourage you from overwriting the reference to the collection because any event handlers which also need the
CollectionChanged
event of the collection will need to be reconnected.I am not sure how notifications are handled if you bind to dependency properties, but if you change your source and it is not a DP you need to notify the binding. This can be done by implementing
INotifyPropertyChanged
.e.g.
Edit: Tested swapping a collection that is stored in a DP, for me it works as expected and the List gets updated, displaying the new collection.