Is there a difference between adding CommandBindin

2019-05-02 09:20发布

Previously I had been using

this.CommandBindings.Add(
    new CommandBinding(ApplicationCommands.Copy, this.cmdCopy_Executed, this.cmdCopy_CanExecute))

where cmdCopy_Executed is a non-static function, but I've seen folks using

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!");
    }

where the CommandBinding is static. Is one preferred over another?

1条回答
霸刀☆藐视天下
2楼-- · 2019-05-02 10:10

The latter is more of a global handler, versus the former which is per instance.

Also, the RegisterClassCommandBinding cannot be unregistered, so you are stuck with it once you register. Generally, when using this it's best to call virtual methods on your control so their behavior can be changed or by-passed.

With CommandBindings you can remove any bindings that are no longer needed. This can also be done by external users of your control. So you may add a command binding that is required, but someone could easily do element.CommandBindings.Clear().

So there are differences, and each has their place. If you want it to be easily customizable, I'd go with the former.

查看更多
登录 后发表回答