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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With