如何使一个 ObservableCollection 依赖于另一个 ObservableCollection
我有包含一些元素的 ObservableCollection。在该集合的某些视图中绑定了一些元素。但有一个元素是特殊的,该元素不能在其他View中显示。因为我希望有其他集合依赖于第一个集合。当然,我可以将元素添加到 ViewModel 中的第一个集合和其他两个集合中,但第一个集合在很多地方发生了变化。因此,从 CollectionChanged 事件中我无法修改第二个集合。如何使一个 ObservableCollection 依赖于另一个 ObservableCollection?
I have ObservableCollection that contains some elements.In some Views to this collection binded some elements. But one element is special, and this element must not displaying in other Views. Because I want have other collection dependent on first collection. Of course, I can add elements to first and two other collections in my ViewModel, but first collection changed in many places. So, from CollectionChanged event I can't modify second collection. How can I make one ObservableCollection dependent on other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我希望我正确理解你的问题:)
我认为你不需要第二/第三/... ObservableCollection。使用 System.Windows.Visibility 类型的 SpecialVisibility 属性(名称由您决定)扩展视图模型。然后,将此属性绑定到数据模板的 Visibility 属性。
这些“特殊”元素(即不应显示的元素)只需将 SpecialVisibility 设置为 System.Windows.Visibility.Collapsed 即可。
当然,这并不能解决同步许多 ObservableCollections 的问题。不过,我认为这可能会解决你的问题。如果使用 CollectionChanged 事件不适合您,您可能需要重构代码。
I hope I understood your problem correctly :)
I don't think you need a second/third/... ObservableCollection. Extend your view model with a SpecialVisibility property (the name is up to you) of type System.Windows.Visibility. Then, bind this property to the Visibility property of your data template.
These 'special' elements (i.e. the elements which should not be dispayed) just need the SpecialVisibility set to System.Windows.Visibility.Collapsed.
Of course, this is not a solution to your problem of synchronizing many ObservableCollections. However, I think this might solve your problem. If using the CollectionChanged event is not an option for you, you might want to restructure your code.
您可以创建一个继承
ObservableCollection
的新类,该类具有对原始集合的引用。这个新类订阅原始类的CollectionChanged
事件,并通过更改自身来对其做出反应。You can create a new class that inherits
ObservableCollection<T>
that has a reference to the original collection. This new class subscribes to theCollectionChanged
event of the original and reacts to it by changing itself.