Is there a difference between adding CommandBindings to a control vs using RegisterClassCommandBinding?

僤鯓⒐⒋嵵緔 提交于 2019-12-07 05:19:38

问题


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:


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.



来源:https://stackoverflow.com/questions/6388701/is-there-a-difference-between-adding-commandbindings-to-a-control-vs-using-regis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!