之前我一直在用
this.CommandBindings.Add(
new CommandBinding(ApplicationCommands.Copy, this.cmdCopy_Executed, this.cmdCopy_CanExecute))
其中 cmdCopy_Executed 是一个非静态函数,但我见过人们使用
static MyControl()
{
CommandBinding binding =
new CommandBinding(ApplicationCommands.Save, CommandHandler);
CommandManager.RegisterClassCommandBinding(typeof(MyControl), binding);
}
private static void CommandHandler(object target, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Command Handled!");
}
CommandBinding 是静态的。一个比另一个更受欢迎吗?
最佳答案
后者更像是一个全局处理程序,而前者是每个实例。
此外,RegisterClassCommandBinding 无法取消注册,因此一旦注册就无法使用。通常,在使用它时,最好在控件上调用虚拟方法,以便可以更改或绕过它们的行为。
使用 CommandBindings,您可以删除不再需要的任何绑定(bind)。这也可以由您的控件的外部用户完成。因此,您可以添加所需的命令绑定(bind),但有人可以轻松地执行 element.CommandBindings.Clear()
。
所以有差异,各有各的位置。如果您希望它易于定制,我会选择前者。
关于c# - 将 CommandBindings 添加到控件与使用 RegisterClassCommandBinding 之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6388701/