WPF:在两个窗口之间共享可观察集合?
我想知道如何在同一项目中的两个不同 WPF 窗口之间共享可观察集合。情况看起来很简单,但我还没有找到解决方案。
我有一个 Window1,它有一个绑定到 obervablecollection 的数据网格,如下所示:
public Window1()
{
InitializeComponent();
_bookLibrary = new ObservableCollection<BOOK>();
datagrid.ItemsSource = _bookLibrary;
}
在 Window1 中,我能够向 _bookLibrary 集合添加/删除 BOOK 对象,并且数据网格正确更新。
我有另一个窗口,Window2。 Window2 使用也能够生成 BOOK 对象的服务引用。我希望能够将 Window2 BOOK 对象添加到位于 Window1 中的 _bookLibrary 集合中(因为 Window1 具有显示整个图书馆的“主”数据网格)。
我可能正在考虑为 Window2 BOOK 对象使用单独的集合,然后将该集合与 Window1 集合合并。
任何想法/建议将不胜感激。谢谢
I was wondering how I would be able to share an observablecollection between two different WPF windows in the same project. The situation seems easy enough, but I have not yet found a solution.
I have Window1 that has a datagrid that is bound to an obervablecollection like so:
public Window1()
{
InitializeComponent();
_bookLibrary = new ObservableCollection<BOOK>();
datagrid.ItemsSource = _bookLibrary;
}
Within Window1, I am able to Add/Remove BOOK objects to/from the _bookLibrary collection and the datagrid updates correctly.
I have another window, Window2. Window2 uses a Service Reference that is also able to generate BOOK objects. I want to be able to add Window2 BOOK objects to the _bookLibrary collection located in Window1 (since Window1 has the "main" datagrid where the entire library is displayed).
I was maybe thinking about using a separate collection for the Window2 BOOK objects and then merge that collection w/ the Window1 collection.
Any ideas / suggestions would be greatly appreciated. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,您必须在架构中引入一个模型,并在两个视图之间共享该模型。因此,您只需在 xaml 中将两个视图绑定到模型的同一属性(集合)即可。
In order to me you have to introduce a Model in your architecture and share that model between the two views. So you just bind in xaml both the view to the same property ( the collection ) of your model.
似乎还有另一种非 MVVM 方法可以通过使用 CollectionViewSource 来完成此操作:
创建您想要的任何
ItemsContainer
(如ListBox
)并引用适当的集合view:...
对 Window2 执行相同操作。
There seems to be another not MVVM way of doing this by using
CollectionViewSource
:Create whatever
ItemsContainer
you want (likeListBox
) and cite the appropriate collection view:...
Do the same for Window2.