如何将多个 ViewModel 嵌套在顶级 ViewModel 中,以一种可以分散在我的视图中的层次结构?

发布于 2024-10-10 21:52:14 字数 860 浏览 3 评论 0原文

现在我有一个相当大的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半城柳色半声笛 2024-10-17 21:52:14

如果将 View 的数据上下文设置为 MainViewModel 并将 SubAVM 公开为如下属性:

public SubViewModel SubAVM { 
   get { 
      return subAVM;
   }
   set{
   if (subAVM == value)
   {
      return;
   }
   subAVM = value; //implement the OnPropertyChanged ...
   }
}

当然,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:

public SubViewModel SubAVM { 
   get { 
      return subAVM;
   }
   set{
   if (subAVM == value)
   {
      return;
   }
   subAVM = value; //implement the OnPropertyChanged ...
   }
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文