如何将多个 ViewModel 嵌套在顶级 ViewModel 中,以一种可以分散在我的视图中的层次结构?
现在我有一个相当大的 ViewModel
,称为 MainViewModel
,其中包含许多命令和属性,可以将它们组织成更合理命名的 ViewModel。
然而,我只有一个窗口,因此需要能够从每个 SubViewModel 中挑选有效的数据和命令......
我认为这可以使用属性来实现,但我不太确定如何在 XAML 中解决这个问题。 (或者如果 ViewModel 本身有暗示)
我意识到我可以在 SubView 上设置我认为合适的 DataContext,但我想避免让我的 View 决定 ViewModel 的层次结构/组织。
前任。伪代码
SubAViewModel mvmB = new SubBViewModel();
SubAViewModel mvmA = new SubAViewModel();
MainViewModel mvm = new MainViewModel( mvmA, mvmB );
<Window DataContext="{StaticResource MainViewModel}">
//This is clearly wrong but is sort of what I am trying to achieve
<MenuItem Command="{Binding Path=MainViewModel.SubAVM.TargetCmd}" />
MenuItem
或其他一些 UserControl
完全有可能想要访问 SubBViewModel
中的命令和 SubAViewModel< 中的属性/代码>。
Right now I have a rather large ViewModel
called MainViewModel
, that contains a lot of commands and properties that could be organized into more reasonably named ViewModels.
I however, only have one window, and so need to be able to cherry-pick the valid data and Commands from each of the SubViewModels....
I figure this could be achieved using properties, but I'm not so sure how to approach this in the XAML. (Or if there is an implication in the ViewModels themselves)
I realize that I can set the DataContext
on SubViews as I see fit, but I want to avoid having my View dictate the hierarchy/organization of my ViewModels.
Ex. pseudo code
SubAViewModel mvmB = new SubBViewModel();
SubAViewModel mvmA = new SubAViewModel();
MainViewModel mvm = new MainViewModel( mvmA, mvmB );
<Window DataContext="{StaticResource MainViewModel}">
//This is clearly wrong but is sort of what I am trying to achieve
<MenuItem Command="{Binding Path=MainViewModel.SubAVM.TargetCmd}" />
It's entirely possible that a MenuItem
or some other UserControl
would want to access a Command in SubBViewModel
and a property in SubAViewModel
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将 View 的数据上下文设置为 MainViewModel 并将 SubAVM 公开为如下属性:
当然,MenuItem 上的 Path 将为 SubAVM.TargetCmd,因为根据依赖关系层次结构,主路径已经是 Menu 的 MainViewModel 。
If you set the data context of the View to the MainViewModel and you expose the SubAVM as a property like this one:
Of course the Path on a MenuItem would be SubAVM.TargetCmd as by the dependency hierarchy the main path is already MainViewModel for a Menu.