我有一个 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);
}
按照教程中的说明创建附加属性。
然后在您的 UI 中绑定(bind)附加属性。
关于c# - 我可以将 RoutedCommand 绑定(bind)到 WPF 中的命令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236874/