c# - 我可以将 RoutedCommand 绑定(bind)到 WPF 中的命令吗?

标签 c# wpf mvvm routed-commands

我有一个 ViewModel 的形式:

class VM : DependencyObject
{
    // This class exposes a command to data binding to delete things from the model
    public static DependencyProperty DeleteProperty = DependencyProperty.Register(/*...*/);

    public static ICommand Delete {
        get {
            return (ICommand)this.GetValue(DeleteProperty);
        }
        set {
            this.SetValue(DeleteProperty, value);
        }
    }
}

对于 ListBoxItem,我想将 ApplicationCommands.Delete 的执行数据绑定(bind)到此 ViewModel 公开的此 ICommand。这样,当有人按下引发 ApplicationCommands.Delete 的菜单项时,如果当前焦点在这件事上,将选择这个特定的删除:

<!-- Elsewhere... -->
<MenuItem Text="Delete" Command="ApplicationCommands.Delete" />

<!-- Some data template with DataContext == the above DependencyObject -->
<Grid>
    <Grid.CommandBindings>
        <!--
        I want ApplicationCommands.Delete to forward to the command {Binding Delete}
        -->
        <CommandBinding Command="ApplicationCommands.Delete" 
                        ???
                        />
    </Grid.CommandBindings>
</Grid>

... 但 CommandBinding 只能绑定(bind)到事件处理程序;不是其他命令,所以我不能使用 MVVM 样式的数据绑定(bind)来附加它。是否有一些我可以在这里使用的 MVVM 机制,或者我是否被迫为 CommandBinding 添加代码隐藏?

最佳答案

您可以使用 this绑定(bind) ApplicationCommand 的教程。
1.在您的 View 模型中添加命令绑定(bind)集合属性:

public CommandBindingCollection CommandBindings { get; }

public YourViewModel()
{
//Create a command binding for the delete command
var deleteBinding = new CommandBinding(ApplicationCommands.Delete, DeleteExecuted, DeleteCanExecute);

//Register the binding to the class
CommandManager.RegisterClassCommandBinding(typeof(YourViewModel), DeleteBinding);

//Adds the binding to the CommandBindingCollection
CommandBindings.Add(deleteBinding);
}
  1. 按照教程中的说明创建附加属性。

  2. 然后在您的 UI 中绑定(bind)附加属性。

关于c# - 我可以将 RoutedCommand 绑定(bind)到 WPF 中的命令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236874/

相关文章:

c# - WP中的MVVM和枢轴控制

c# - 获取错误 'xargs' 未被识别为内部或外部命令。通过 Windows 为 iOS 运行 appium 测试时

c# - Xamarin Studio Storyboard​​空白

MVVM Binding - 在 View 中创建控件,如何绑定(bind)到 ViewModel 中的属性?

c# - WPF 命令 - 从 Window 和 UserControl 调用,相同的处理程序

WPF 使用 DataTemplate 隐式选择模板,但在 'List' 之外

WPF M-V-VM : Get selected items from a ListCollectionView?

c# - 泛型:为什么编译器不能在这种情况下推断类型参数?

c# - ResolveURL 未在用户控件中解析

wpf - 单击鼠标后如何停止 TreeView 折叠事件