将多个树视图的属性绑定到同一个 ViewModel
我正在开发 MVVM 实现,其中我将生成多个视图(并排),每个视图包含一个树控件。
每个视图都有一个类似的树,其中包含[几乎]所有相同项目的副本。
我想同步所有视图/TreeView 上的 IsExpanded 属性。
意思是,如果我折叠一个节点,我希望所有节点都折叠(有些用于列宽等)。
实现此目的的一种方法是将所有视图绑定到同一个视图模型,并在该 ViewModel 上具有 DependencyProperty,并在每个视图上将绑定设置为双向。但是,我需要将每个视图绑定到单独的视图模型,以便它可以显示唯一的值。我只需要同步树的一些属性,例如 IsExpanded 和 Width。
这里最好的方法是什么?
I am working on a MVVM implementation, where i'll spawn multiple views (side by side) each containing a tree control.
each of the views will have a similar tree, with a copy of [almost] all the same items.
I would like to synchronize the IsExpanded property on all the view/TreeView's..
meaning, if i collapse one node, i would like all of them to collapse (and some goes for column widths etc).
One way to do this, would be to bind all views to the same viewmodel, and have a DependencyProperty on that ViewModel, and set up the binding as Two Way on each view. However, i need each view to be bound to a separate viewmodel so that it can display unique values. I just need to synchronize a few properties of the tree, such as IsExpanded and Width.
What would be the best approach here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 Prism 和 EventAggregator 服务,用于在视图模型之间交换数据。
You can use Prism and EventAggregator service from it to exchange data between view models.
如果这是最佳设计选项,那么您没有理由不能在单个 ViewModel 中拥有不同的集合。特别是如果您的多个树/集合是从某些“完整集”中过滤出来的;这实际上可能更有意义。
只需将多个集合添加到您的 ViewModel 中并绑定到它们即可。
并且您的视图应该相应地绑定
为了澄清,我建议您对所有这些包含树的视图使用单个 ViewModel。
There's no reason you can't have different collections within a single ViewModel, if that is the best design option. Especially if your multiple Trees / Collections are filtered from some 'complete set'; it might actually make more sense.
Just add multiple collections to your ViewModel, and bind to them.
and your Views should bind accordingly
To clarify, I'm suggesting that you use a single ViewModel for all of these Tree-containing Views.
ViewModel 不需要 DependencyPropery——它只需要公开一个实现 INotifyPropertyChanged 的属性。
两个 ViewModel 需要以某种方式共享状态,并公开表示该状态的属性。如何共享状态在很大程度上取决于 ViewModel 的实例化方式(可能还有其他因素)。例如,如果您的两个虚拟机由某个父对象实例化,则父对象可能会创建一个实例并将其传递给两个虚拟机的构造函数。
The ViewModel won't need a DependencyPropery--it will just need to expose a property that implements INotifyPropertyChanged.
The two ViewModels will need to have some way of sharing state, and exposing a property that represents that state. How you share the state depends heavily on how your ViewModels are instantiated (and probably other factors). For example, if your two VMs are being instantiated by some parent object, the parent may create one instance and pass it to both VMs in their constructors.
如果使用 xaml 显示树视图,则可以将每个树视图绑定到生成的第一个树视图。
例如,您可以使用如下所示的绑定:
If you display the treeview's using xaml, you can bind every treeview to the first treeview spawned.
For example you can use some binding like this: