WPF Two Commands handlers, One Command

假如想象 提交于 2020-01-22 15:21:09

问题


Im deriving from a third party control. It is implementing ApplicationCommands.SelectAll. However the behaviour i want is slightly different. there is no virtual method i can override, and when i register a class handler, like so

     CommandManager.RegisterClassCommandBinding(typeof(MyDerivedControl), new CommandBinding(ApplicationCommands.SelectAll, new ExecutedRoutedEventHandler(OnExecutedSelectAll), new CanExecuteRoutedEventHandler(OnCanExecuteSelectAll)));

My methods do not get called. The third party control i am deriving from is marking

e.Handled=true;

in its command handlers ( i know this cause i have seen the source, but i cant modify it )

What can i do?


回答1:


You have three options:

1) You can register your CommandBinding to handle preview events instead of or in addition to regular events:

CommandBinding cb = new CommandBinding(ApplicationCommands.SelectAll);
cb.PreviewCanExecute += OnCanExecuteSelectAll;
cb.PreviewExecuted += OnExecutedSelectAll;

but beware - when registering handlers through CommandBinding if you have PreviewExecuted registered, the Executed handler will never run even if you explicitly set the e.Handled to false. It does work as expected for PreviewCanExecute/CanExecute pair of events though. This is the way CommandBinding class is implemented.
So use PreviewExecuted only if you do not want the base class command handler to run.

2) Alternatively you can register your command handlers through CommandManager directly:

CommandManager.AddPreviewCanExecuteHandler(this, OnCanExecuteSelectAll);
CommandManager.AddPreviewExecutedHandler(this, OnExecutedSelectAll);

This is not a class handler though so you'd need to do it for each instance. Then in your handler you'd need to check weather this is the command you're interested in (there is a reference to the command in event args). Note: you'll still have to register CommandBinding, but if you're going to only add handlers directly on CommandManager - you don't need to register any handlers with that Command Binding.

3) Or you can do a bit of a hack(not really a hack):

this.AddHandler(CommandManager.CanExecuteEvent, new CanExecuteRoutedEventHandler(OnCanExecuteSelectAll), true);
this.AddHandler(CommandManager.ExecutedEvent, new ExecutedRoutedEventHandler(OnExecutedSelectAll), true);

this way you register command event handlers so that they will be executed even if they were already handled.
As with the point above you'll need to register command binding in order for the CommandManager events to be fired.
This is almost the same stuff that is in the point 2 above, but when you call CommandManager.Add[one of the four events]Handler - the command manager calls AddHandler on the control using two argument version.



来源:https://stackoverflow.com/questions/2445106/wpf-two-commands-handlers-one-command

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