c# - 将 CommandBindings 添加到控件与使用 RegisterClassCommandBinding 之间有区别吗?

标签 c# wpf static commandbinding

之前我一直在用

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/

相关文章:

java - 如何将文本文件中的内容存储到数组列表

java - 静态 token 生成?

c# - 在 C# 中将字符串/整数转换为上标

c# - 应用程序如何正确崩溃?

wpf - 密码框绑定(bind)

c# - 使用 `ElementName` 的 WPF 绑定(bind)失败,但在 Path 属性中指定 ElementName 有效吗?

c# - String.Format 和 string.Format(以及原始数据类型的其他静态成员)之间有什么区别?

c# - 如何在 PropertyGrid TypeConversion 中获取旧值?

c# - Windows Phone 8.1 XAML 广告中介

c# - 只有一行的方法会影响性能吗?