【问题标题】:MVVM Command Routing Between Controls控件之间的 MVVM 命令路由
【发布时间】:2009-11-02 22:06:07
【问题描述】:

我目前有一个带有 Button 和 ContentPresenter 的主视图,它绑定到 ViewModel 的一个属性,该属性是另一个 View(和关联的 ViewModel)。有没有办法从 ContentPresenter 中加载的控件中声明的处理程序路由命令?我这样做的原因是主视图包含工具栏,而内容演示​​者具有内容。我正在使用 Microsoft MVVM 模板和生成的 DelegateCommand 类。

<Window ...>
   <Button x:Name="btnAction" Command="{Binding ActionCommand}" />
   <ContentPresenter Content="{Binding CurrentView}" />
</Window>

【问题讨论】:

    标签: wpf mvvm routed-commands


    【解决方案1】:

    您应该创建一个命令对象,它是类上的一个静态对象,窗口和控件都可以看到。

      public static class MyCommands
      {
         public static RoutedUICommend CoolCommand .....;
      }
    

    然后可以将控件的Command属性绑定到命令对象上,例如:

    <Button Command="cmd:MyCommands.CoolCommand" />
    

    然后您只需要使用 CommandBinding XAML 元素在窗口级别处理命令绑定。

    <CommandBinding Command="cmd:MyCommands.CoolCommand" Executed="My_Handler" />
    

    【讨论】:

    • 似乎是个好主意。出于好奇,拥有一个用于将内容链接在一起的共享命令存储库是一种常见的 WPF 做法吗?
    • 这并不是将东西链接在一起的标准做法。当您需要将命令绑定到不以其他方式共享绑定的命令处理程序时,这是一种更常见的做法。这与内置 WPF cmets 使用的机制(如 ApplicationCommands)基本相同。
    猜你喜欢
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多