如何在MVVM中使用ApplicationCommands

时间:2016-01-26 20:23:59

标签: c# wpf mvvm

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

这似乎是常见的,但信息似乎非常有限。这通常是如何实现的? (使用或不使用PRISM,MVVM Light,......)

旧答案:

How to bind ApplicationCommands to a ViewModel但我觉得使用行为解决这个问题似乎很奇怪

WPF - Handle an ApplicationCommand in the ViewModel但我并不认为MVVM符合公认的答案。

在旧文章中使用附加属性:CommandBindings with MVVM引用另一篇文章。

1 个答案:

答案 0 :(得分:0)

自从我提出这个问题以来已经有一段时间了,但看起来很多人都在关注这个问题。我最终使用了一个将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>