0

静态类ApplicationCommands由许多RoutedUICommands 组成,其中一些可能是纯粹基于视图的命令(撤消/重做、剪切/复制/粘贴),但其他的最终需要使用视图模型。但是,当使用后面的命令之一时,例如Save,没有干净的方法将命令传播到视图模型:

<CommandBindings>
    <CommandBinding Command="Save" Executed="Save_Executed" />
</CommandBindings>
....
<MenuItem Command="Save" />

这将调用Save_Executed代码隐藏类上的事件处理程序,因为它将在 MVP 模式中使用,但它不允许我将命令移动到 MVVM 中的视图模型,除非在Save_Executed事件处理程序中使用这条丑陋的行:

((ViewModel1)this.DataContext).Save();

这也与其他命令完全不一致,比如RelayCommand直接在视图模型中定义的s。由于所有这些不便,我的印象是 ApplicationCommands 在设计时只考虑了 MVP,而不是 MVVM。

需要传播到视图模型的命令是否完全可用?

4

2 回答 2

0

如果我正确理解您的问题,我认为如果您像这样处理它,您可以按照您的要求做。

你的视图模型

// Call this from your ctor
 private void InitializeCommandBindings()
    {
        this.CommandBindings = new CommandBindingCollection(new[]
            {                   
        new CommandBinding(
                    ApplicationCommands.Save,
                    new ExecutedRoutedEventHandler(YourEventHandler),
                    new CanExecuteRoutedEventHandler((sender, e) => e.CanExecute = Your Logic...))
});
}

你的看法

<Button Command="{x:Static ApplicationCommands.Save}"/>
于 2012-10-10T16:02:35.737 回答
0

您需要将绑定添加到视图

this.CommandBindings.AddRange(((MainViewModel)this.DataContext).CommandBindings);
于 2014-01-03T09:59:35.853 回答