WPF學習筆記(24)命令與ICommand接口

命令與ICommand接口

  • 一、命令
    • 1. ICommandSource
    • 2. 示例
    • 3. CommandBinding
  • 二、ICommand
    • 1.ICommand接口
    • 2. ICommand用法
    • 3. CanExecute
  • 總結


一、命令

在這里插入圖片描述
官方文檔:https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/advanced/commanding-overview

1. ICommandSource

在這里插入圖片描述
官方文檔:https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/advanced/how-to-implement-icommandsource

在這里插入圖片描述

2. 示例

在這里插入圖片描述
在這里插入圖片描述

    <Grid><TextBox x:Name="textBox" Text="TextBox" VerticalAlignment="Top"  Height="150" Margin="219,35,187,0"/><Button x:Name="buttonCut"Content="剪切"Command="ApplicationCommands.Cut"CommandTarget="{Binding ElementName=textBox}"Height="100" Margin="219,233,419,102"/><Button x:Name="buttonPaste"Content="粘貼"Command="ApplicationCommands.Paste"CommandTarget="{Binding ElementName=textBox}" Margin="453,233,187,107"/></Grid>

在這里插入圖片描述

3. CommandBinding

在這里插入圖片描述
在這里插入圖片描述

  • 當TEXTBOX內容長度大于0時,CanExecute被判斷為true
  • true可以啟用命令源按鈕,false禁用按鈕
    在這里插入圖片描述
<Window.CommandBindings><CommandBinding Command="ApplicationCommands.Cut" CanExecute="my_CanExecute" Executed="my_Execute"/>
</Window.CommandBindings><Grid><TextBox x:Name="textBox" Text="TextBox" VerticalAlignment="Top"  Height="150" Margin="219,35,187,0"/><Button x:Name="buttonCut" Margin="219,233,419,102" Height="100" Content="剪切"Command="ApplicationCommands.Cut"/><Button x:Name="buttonPaste"Content="粘貼"Command="ApplicationCommands.Paste"CommandTarget="{Binding ElementName=textBox}"Margin="453,233,187,107"/>
</Grid>
public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();}private void my_Execute(object sender, ExecutedRoutedEventArgs e){Console.WriteLine("Execute!!!");textBox.Cut();}private void my_CanExecute(object sender, CanExecuteRoutedEventArgs e){e.CanExecute = textBox.SelectionLength > 0;}
}

二、ICommand

在這里插入圖片描述

官方文檔:https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.input.icommand?view=net-9.0

1.ICommand接口

在這里插入圖片描述

ICommand接口的屬性與事件如下:
在這里插入圖片描述

2. ICommand用法

在這里插入圖片描述

    <Grid><TextBox HorizontalAlignment="Left" Margin="222,62,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="422" Height="102"/><Button x:Name="button1" Content="  自定義命令" HorizontalAlignment="Left" Margin="222,217,0,0" VerticalAlignment="Top" Height="64" Width="145"/><Button x:Name="button2" Content="觸發事件" HorizontalAlignment="Left" Margin="499,217,0,0" VerticalAlignment="Top" Height="64" Width="145"/></Grid>

在MainWindow.xaml.cs文件內自定義命令接口
在這里插入圖片描述
在這里插入圖片描述

<Window.Resources><local:MyCommand x:Key="MyCMD" />
</Window.Resources>
<Grid><TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="222,62,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="422" Height="102"/><Button x:Name="button1" Content="  自定義命令"Command="{StaticResource MyCMD}"CommandParameter="{Binding ElementName=textBox,Path=Text}"HorizontalAlignment="Left" Margin="222,217,0,0" VerticalAlignment="Top" Height="64" Width="145"/><Button x:Name="button2" Content="觸發事件" HorizontalAlignment="Left" Margin="499,217,0,0" VerticalAlignment="Top" Height="64" Width="145"/>
</Grid>
public class MyCommand : ICommand
{public event EventHandler CanExecuteChanged;public bool CanExecute(object parameter){return true;//按鈕可以點擊//return false;//按鈕不可點擊}//Execute方法中實現命令處理邏輯public void Execute(object parameter){MessageBox.Show(parameter.ToString());}
}

以下為CanExecuteChanged的事件解釋:
在這里插入圖片描述

public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();}private void button2_Click(object sender, RoutedEventArgs e){MyCommand c = Resources["MyCMD"] as MyCommand;//觸發CanExecuteChangedc.RaiseCanExecuteChanged();}
}
//實現ICommand接口
public class MyCommand : ICommand
{public event EventHandler CanExecuteChanged;public bool CanExecute(object parameter){String str = parameter as String;return str?.Length > 0;//return true;//按鈕可以點擊//return false;//按鈕不可點擊}//Execute方法中實現命令處理邏輯public void Execute(object parameter){MessageBox.Show(parameter.ToString());}//定義一個方法,手動觸發CanExecuteChanged事件public void RaiseCanExecuteChanged() {//表面上,沒有為 CanExecuteChanged 這個事件添加任何訂閱方法//例如CanExecuteChanged += fun;//但是我們為按鈕設置命令時,自動加入了一個此事件訂閱的方法,//并且這個訂閱的方法,會去調用命令的CanExecute//可通過Delegate查看CanExecuteChanged的來源與內容Delegate[] delegates = CanExecuteChanged.GetInvocationList();//delegates內查看到 System.Windows.Input.CanExecuteChangedEventManager+HandlerSink"//OnCanExecuteChangedCanExecuteChanged?.Invoke(this, EventArgs.Empty);}

加粗樣式

3. CanExecute

以ButtonBase為例介紹,調用了OnCommandChanged
在這里插入圖片描述
OnCommandChanged調用了HookCommand
在這里插入圖片描述

HookCommand調用了AddHandler,CanExecute調用了CanExecuteCommandSource在這里插入圖片描述
在這里插入圖片描述
AddHandler調用的PrivateAddHandler又new 了一個HandlerSink
在這里插入圖片描述

HandlerSink將OnCommandChanged函數添加到Icommand接口的CanExecuteChanged
在這里插入圖片描述

在這里插入圖片描述
在這里插入圖片描述

總結

關于ButtonBase、CanExecuteChangedEventManager、commandHelpers的詳細原理、我們可以參考WPF框架的源碼
https://github.com/dotnet/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/Primitives/ButtonBase.cs
https://github.com/dotnet/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Input/Command/CanExecuteRoutedEventArgs.cs
https://github.com/dotnet/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/Commands/CommandHelpers.cs

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/87872.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/87872.shtml
英文地址,請注明出處:http://en.pswp.cn/web/87872.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

TCP長連接保持在線狀態

TCP長連接是指在一次TCP連接建立后&#xff0c;保持連接狀態較長時間&#xff0c;用于多次數據傳輸&#xff0c;而不是每次通信后立即斷開。這種機制對于需要頻繁通信的應用非常重要。 保持TCP長連接在線的方法 1. 心跳機制(Heartbeat) 實現原理&#xff1a;定期發送小數據包…

華為OD機試 2025B卷 - 報文響應時間 (C++ Python JAVA JS C語言)

2025B卷目錄點擊查看: 華為OD機試2025B卷真題題庫目錄|機考題庫 + 算法考點詳解 2025B卷 100分題型 題目描述 IGMP 協議中,有一個字段稱作最大響應時間 (Max Response Time) ,HOST收到查詢報文,解折出 MaxResponsetime 字段后,需要在 (0,MaxResponseTime] 時間 (s) 內選…

深入理解微服務中的服務注冊與發現(Consul)

在當今數字化浪潮下&#xff0c;微服務架構憑借其高內聚、低耦合的特性&#xff0c;成為眾多企業構建復雜應用系統的首選方案。然而&#xff0c;隨著服務數量的不斷增加&#xff0c;服務之間的調用與管理變得愈發復雜。這時&#xff0c;服務注冊與發現就如同微服務架構中的 “導…

Zephyr【2】-----內核調度[1]

內核調度 Zephyr 內核的調度器是基于什么原則選擇當前執行線程的&#xff1f; 總是選擇優先級最高的就緒線程作為當前線程。 當多個線程優先級相同時&#xff0c;調度器會如何選擇&#xff1f; 線程的 “就緒狀態” 和 “非就緒狀態” 分別指什么&#xff1f;哪些情況會導致…

LangChain內置工具包和聯網搜索

目錄 一、什么是智能體?工具包又是什么&#xff1f; 二、智能體(Agent)的出現是為了解決哪些問題&#xff1f; 三、LangChain里面創建工具方式 3.1 tool 裝飾器&#xff1a;用來定義一個簡單的工具函數,, 可以直接給函數加上這個裝飾器&#xff0c;讓函數成為可調用的工具…

用c++做游戲開發至少要掌握哪些知識?

成長路上不孤單&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a; 【14后&#x1f60a;///C愛好者&#x1f60a;///持續分享所學&#x1f60a;///如有需要歡迎收藏轉發///&#x1f60a;】 今日分享關于用C做游戲開發的相關內容&#xff01; 關…

vue3使用summernote

一、安裝 npm install summernote-vue jquery summernote bootstrap popperjs/core二、summernoteEditor.vue <template><div ref"editorRef"></div> </template><script setup> import {ref, onMounted, onBeforeUnmount, watch} f…

低代碼平臺的性能測試實踐與挑戰

一、引言 近年來&#xff0c;低代碼平臺&#xff08;Low-Code Platform&#xff09;正在快速改變企業軟件開發方式。Gartner 預測&#xff0c;到 2025 年&#xff0c;超過 70% 的應用開發將基于低代碼或無代碼技術。通過“拖拉拽建模 圖形化邏輯 一鍵發布”&#xff0c;企業…

Stereolabs ZED系列與ZED X立體相機系列對比:如何根據項目需求選擇?

Stereolabs是全球領先的三維視覺技術公司&#xff0c;專注于為機器人、自動化和空間感知等領域提供高性能視覺解決方案。其ZED立體相機系列包括ZED和ZED X兩大系列&#xff0c;分別針對多場景三維感知和工業級應用設計&#xff0c;為企業和開發者提供了豐富的選擇。ZED系列&…

Spring Boot登錄認證實現學習心得:從皮膚信息系統項目中學到的經驗

前言 最近通過一個皮膚信息管理系統的項目實踐&#xff0c;深入學習了Spring Boot框架中登錄認證功能的實現方式。這個項目涵蓋了從后端配置到前端集成的完整流程&#xff0c;讓我對現代Web應用的安全機制有了更深刻的理解。本文將分享我在這個過程中的學習心得和技術要點。 …

【初階數據結構】雙向鏈表

文章目錄 雙向鏈表1.申請節點2.鏈表初始化3.尾插4.打印鏈表5.頭插6.尾刪7.頭刪8.查找9.指定位置插入10.刪除pos節點11.鏈表的銷毀12.程序源碼 雙向鏈表 鏈表分類 8種 (帶頭/不帶頭 單向/雙向 循環/循環) 最常用兩種 單鏈表(不帶頭單向不循環鏈表) 雙向鏈表&#xff08;帶頭雙向…

從 Prompt 管理到人格穩定:探索 Cursor AI 編輯器如何賦能 Prompt 工程與人格風格設計(下)

六、引入 Cursor AI 編輯器的開發流程革新 在整個系統開發過程中&#xff0c;我大量采用了 Cursor 編輯器作為主要的開發環境&#xff0c;并獲得以下關鍵收益&#xff1a; 具備 AI 補全與代碼聯想功能&#xff1a;支持通過內置 Copilot 模型對 Python、FastAPI、YAML、JSON 等…

Spark運行架構

Spark框架的核心是一個計算引擎&#xff0c;整體來說&#xff0c;它采用了標準master-slave的結構 ?如下圖所示&#xff0c;它展示了一個Spark執行時的基本結構&#xff0c;圖形中的Driver表示master&#xff0c;負責管理整個集群中的作業任務調度&#xff0c;圖形中的Executo…

基于未合入PR創建增量patch的git管理方法

目錄前言準備操作步驟精準移植基礎PR到本地分支修改代碼鴻蒙編譯、調試、測試具體編譯指令、測試步驟這里帶過&#xff0c;這不是本文論述重點創建diff文件工作倉庫應用最新patch總結前言 作為程序員&#xff0c;多人協同開發同一個需求是正常的。即使是自己一個人搞需求&…

git真正更新項目

背景 Fetch all remote后flutter代碼都拉下來&#xff0c;都是Android項目應用不上&#xff1b;git–>update project才生效&#xff01;&#xff01;&#xff01;

AI時代如何拓展Web前端開發的邊界

文章目錄 1 從“頁面仔”到“智能體驗構建者”——前端的變與不變2 AI 如何重塑 Web 前端&#xff1a;從開發到用戶體驗的革命2.1 AI 賦能開發效率&#xff1a;前端工程師的“超級外掛”2.1.1 智能代碼輔助與生成2.1.2 自動化測試與 Bug 定位 2.2 AI 提升用戶體驗&#xff0c;構…

chrome webdrive異常處理-session not created falled opening key——仙盟創夢IDE

注冊表錯誤 :EKKOK:chromeinstallerut1 Lgoogle update settings.cc:26b falled opening key .( e\Update\ClientStateMedium 8A69D345-D564-463c-AFF1-A69D9E530F96} to set usagestats 連接超時 disconnected: received Inspector.detached eventfailed to check if windo…

【Java EE初階 --- 多線程(進階)】JUC

樂觀學習&#xff0c;樂觀生活&#xff0c;才能不斷前進啊&#xff01;&#xff01;&#xff01; 我的主頁&#xff1a;optimistic_chen 我的專欄&#xff1a;c語言 &#xff0c;Java 歡迎大家訪問~ 創作不易&#xff0c;大佬們點贊鼓勵下吧~ 文章目錄 JUC組件ReentrantLock與s…

免費靜態網站搭建

免費靜態網站搭建 內容簡介搭建步驟GitHub倉庫創建Jekyll安裝使用Jekyll安裝指南Jekyll快速搭建測試Jekyll后續玩法 內容簡介 &#x1f6a9;Tech Contents&#xff1a;GithubPage/Jekyll/Custom URLs &#x1f431;GitHub Pages&#xff1a;靜態網站托管服務&#xff0c;自動將…

MySQL 8.0 OCP 1Z0-908 題目解析(21)

題目81 Choose two. Examine the modified output: mysql> SHOW SLAVE STATUS\G *************************** 1. row ***************************Slave_IO_Running: YesSlave_SQL_Running: YesSeconds_Behind_Master: 1612Seconds_Behind_Master value is steadily gro…