如何在 MVVM 中使用应用程序命令

本文关键字:应用程序 命令 MVVM | 更新日期: 2023-09-27 18:31:56

我想使用 ApplicationCommand.剪切、复制、粘贴、保存,...它们看起来很有趣,因为命令路由、键绑定以及某些控件使用它们的事实。我了解如何绑定到 VM 上的中继/委托命令,但我似乎无法了解应用程序命令。我找到了几个旧的答案,但没有其他信息,我有点不愿意遵循这些路线。

这似乎是很常见的事情,但信息似乎非常有限。通常如何实现这一点?(无论是否使用PRISM,MVVM Light等)

旧答案:

如何将应用程序命令绑定到 ViewModel,但这对我来说似乎很奇怪,使用行为来解决这个问题

WPF - 在视图模型中处理应用程序命令,但我认为这不是接受答案中的 MVVM。

在旧文章中使用附加属性:引用另一篇文章的 MVVM 的命令绑定。

如何在 MVVM 中使用应用程序命令

自从我问这个问题以来已经有一段时间了,但看起来很多人都在看它。我最终使用了将 VM 命令列表连接到 FrameworkElement 的行为。这似乎是最灵活和可重用的解决方案。

public class AttachCommandBindingsBehavior : Behavior<FrameworkElement>
{
    public ObservableCollection<CommandBinding> CommandBindings
    {
        get
        {
            return (ObservableCollection<CommandBinding>)GetValue(CommandBindingsProperty);
        }
        set
        {
            SetValue(CommandBindingsProperty, value);
        }
    }
    public static readonly DependencyProperty CommandBindingsProperty = DependencyProperty.Register("CommandBindings", typeof(ObservableCollection<CommandBinding>), typeof(AttachCommandBindingsBehavior), new PropertyMetadata(null, OnCommandBindingsChanged));
    private static void OnCommandBindingsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        AttachCommandBindingsBehavior attachCommandBindingsBehavior = (AttachCommandBindingsBehavior)sender;
        if (attachCommandBindingsBehavior == null)
            return;
        ObservableCollection<CommandBinding> commandBindings = (ObservableCollection<CommandBinding>)e.NewValue;
        if (commandBindings != null)
        {
            if (attachCommandBindingsBehavior.CommandBindings != null)
                attachCommandBindingsBehavior.CommandBindings.CollectionChanged -= attachCommandBindingsBehavior.CommandBindings_CollectionChanged;
            attachCommandBindingsBehavior.CommandBindings.CollectionChanged += attachCommandBindingsBehavior.CommandBindings_CollectionChanged;
        }
    }
    void CommandBindings_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        ObservableCollection<CommandBinding> collection = (ObservableCollection<CommandBinding>)sender;
        if (collection != null)
        {
            foreach (CommandBinding commandBinding in collection)
                AssociatedObject.CommandBindings.Add(commandBinding);
        }
    }
}

在 xaml 中,您可以执行以下操作:

<i:Interaction.Behaviors>
    <localBehaviors:AttachCommandBindingsBehavior CommandBindings="{Binding CommandBindings}"/>
</i:Interaction.Behaviors>