【问题标题】:MVVM-Calling commands on child viewModel子视图模型上的 MVVM 调用命令
【发布时间】:2013-07-26 07:39:27
【问题描述】:

我正在使用 MVVM 并且有一个带有关闭按钮的主窗口,并且它绑定到 MainWindowViewModel 的 ICommand 命令。 在主窗口中有两个UserControl1和UserControl2,分别绑定到视图模型UserControlVM1和UserControlVM2。

UserControlVM1 和 UserControlVM2 有一个名为 CleanUp 的命令,用于清理资源。

所以每当在主窗口上单击关闭按钮时,我都想调用 Usercontrol 视图模型的 CleanUp 命令。我们如何在 XAML 或任何其他替代方案中做到这一点?

【问题讨论】:

  • 您的 MainWindowVM 是否引用了这些子 ViewModel ?上级的东西应该对这些有参考,以便 MainWindowVM 可以了解它们。或者也许...

标签: wpf mvvm


【解决方案1】:

ViewModels 之间通信的常见实现是 Mediator Pattern,它描述了您的 ViewModels 之间的公共对象,提供了一个 Publish/Subscribe 模型。当感兴趣的Event 出现在一个对象中时,它publishes 将通知Mediator,然后将Mediator 的一个或多个subscribed 到特定Event 的对象通知@987654332 @ 出现在原始对象中。

Mediator Pattern Example

【讨论】:

    【解决方案2】:

    您应该考虑使用视图模型优先的方法,在这种情况下,MainWindowViewModel 将引用UserControlVM1UserControlVM2,并且可以直接调用CleanUp 方法。

    你应该考虑using an MVVM framework if you're using MVVM

    【讨论】:

      【解决方案3】:

      您可以从Prism's developer guide 的技术中获得灵感。

      在 Patterns and Practices 的 Prism 框架中,CompositeCommand 允许多个 ViewModel 针对单个 CompositeCommand 注册自己的命令,这样就可以通过一次调用来调用所有的命令。 您还需要在所有 ViewModel 中引用的这个全局类,但不一定是静态的,因为您没有松散耦合的模块。

      【讨论】:

        猜你喜欢
        • 2010-11-28
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-30
        • 2013-01-16
        • 1970-01-01
        相关资源
        最近更新 更多