WPF之坑——ICommandSource与RoutedUICommand
最近在項目中自己寫了一個控件A,繼承自contentcontrol,實現了icommandsource接口。(因需求特殊并沒有使用buttonbase及它的派生類為基類),控件A在測試程序中運轉良好,綁定的命令響應方法能夠被正確執行。下邊代碼是控件A執行命令的部分:
RoutedEventArgs rea = new RoutedEventArgs(Button.ClickEvent, this); RaiseEvent(rea);if (!rea.Handled && Command != null) {Command.Execute(CommandParameter); }
但在實現項目中,我將控件A放在了另一個較為復制雜的控件B的template中,并在控件B的commandbindings中設置了命令綁定,命令使用的是WPF原生命令類型RoutedUICommand。這個時候詭異的事件發生了,不論我怎么在template里邊設置控件A的commandtarget屬性,上邊代碼執行了Command.Execute(CommandParameter)這句之后,B綁定的命令響應方法都不會被調用。
之后在群里問了一些大神,都沒有得到解決方法,于是乎查了下.net碼源,看看buttonbase是如何處理這個問題。
不看不知道,一看嚇一跳,在buttonbase中處理命令時,用到了大量的.net項目里的internal類或方法(微軟這是成心留一手啊!)
#from buttonbase.cs/// <summary> /// This virtual method is called when button is clicked and it raises the Click event /// </summary> protected virtual void OnClick() {RoutedEventArgs newEvent = new RoutedEventArgs(ButtonBase.ClickEvent, this);RaiseEvent(newEvent);MS.Internal.Commands.CommandHelpers.ExecuteCommandSource(this); }
#from?CommandHelpers.cs
internal static void ExecuteCommandSource(ICommandSource commandSource) {CriticalExecuteCommandSource(commandSource, false);}internal static void CriticalExecuteCommandSource(ICommandSource commandSource, bool userInitiated) {ICommand command = commandSource.Command;if (command != null){object parameter = commandSource.CommandParameter;IInputElement target = commandSource.CommandTarget;RoutedCommand routed = command as RoutedCommand;if (routed != null){if (target == null){target = commandSource as IInputElement;}if (routed.CanExecute(parameter, target)){routed.ExecuteCore(parameter, target, userInitiated);}}else if (command.CanExecute(parameter)){command.Execute(parameter);}} }從上邊.net這幾段代碼里我們可以看到,buttonbase在執行命令里的時候,使用的是?CommandHelpers這個內部類中定義的方法,而這個方法的核心邏輯是先判斷使用的命令是不是RoutedCommand類型,如果是的話則可能會使用RoutedCommand的內方法ExecuteCore去執行命令,而在這個方法中才有commandtarget這個參數。
總結一下,如果你的控件不是繼承自buttonbase,那么就不能使用RoutedCommand.RoutedCommand這個內部方法,不能使用這個內部方法那么RoutedCommand就不會認你自己設置的commandtarget,那么如果.net庫自己找到target不對,你再怎么設置也是徒勞。。。(我感覺被微軟深深傷害了)
說明白點,不要把自己實現icommandsource的類型與routedcommand搭配使用!
轉載于:https://www.cnblogs.com/GuoRL/p/5778868.html
總結
以上是生活随笔為你收集整理的WPF之坑——ICommandSource与RoutedUICommand的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Solr学习之一 --------环境搭
- 下一篇: 吐槽一下博客园