日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

WPF之坑——ICommandSource与RoutedUICommand

發布時間:2025/4/9 asp.net 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。