WPF-20 ICommand命令綁定

這節我們介紹一下WPF中比較重要的接口ICommand,也是WPF中一個新的特性,做過WinForm朋友都知道,WinForm開發是基于事件驅動開發模式,比如一個Button有Click事件,當我點擊該按鈕時,在當前頁面會執行具體的業務,這樣帶來的UI和業務層產生緊密的耦合,WPF也繼承了WinForm這一舊的開發模式,同時給我們添加了新的方法,使得UI和后端業務完全隔離,從而UI和業務邏輯解耦,我們來看一下該接口的定義:

public interface ICommand{event?EventHandler?CanExecuteChanged;bool?CanExecute(object?parameter);void Execute(object parameter);}

在整個MVVM架構中該接口起著非常重要的作用,我們來看一下該接口成員,CanExecuteChanged事件觸發通知UI界面做出響應,比如按鈕禁用或啟用,表示CanExecute該接口返回一個bool值,表示是否執行命令,返回true,命令執行,false命令不執行。

我們通過一個簡單的例子實現命令綁定,需求比較簡單:我們定義一個輸入框,如果為空狀態,提交按鈕禁用,如果有值,按鈕啟用,點擊提交,并將值顯示到頁面。

我們定義一個DelegateCommand 實現ICommand接口:

public class DelegateCommand : ICommand{private Action _execute;private?Func<bool>?_canExecute;public DelegateCommand(Action executeMethod){_execute = executeMethod;}public DelegateCommand(Action executeMethod, Func<bool> canExecute): this(executeMethod){this._canExecute = canExecute;}public bool CanExecute(object parameter){return _canExecute();}public event EventHandler CanExecuteChanged {add{CommandManager.RequerySuggested += value;}remove{CommandManager.RequerySuggested -= value;}}public void Execute(object parameter){_execute();}}

接下來我們定義一個ViewMode類,命名為SampleViewModel實現INotifyPropertyChanged接口

public class SampleViewModel : INotifyPropertyChanged{public event PropertyChangedEventHandler PropertyChanged;private void NotifyPropertyChanged([CallerMemberName] String propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private string name = String.Empty;public string Name{get{return name;}set{if (value != this.name){this.name = value;NotifyPropertyChanged();}}}private string displayName = string.Empty;public string DisplayName{get { return displayName; }set{if (value != this.displayName){displayName = value;NotifyPropertyChanged();}}}ICommand delegateCommand;public ICommand DelegateCommand{get{if (delegateCommand == null){delegateCommand = new DelegateCommand(Execute, CanExecute);}return delegateCommand;}}public void Execute(){DisplayName = Name;}public bool CanExecute(){return !string.IsNullOrEmpty(Name);}}

? XMLA頁面定義:

<Window x:Class="Example_21.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Example_21"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition></RowDefinition><RowDefinition></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><TextBox Grid.Row="0" Name="txtBox" Width="200" Text="{Binding Path=Name,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center"/><TextBlock Grid.Row="1" Width="200" Text="{Binding Path=DisplayName}"></TextBlock><Button Grid.Row="2" x:Uid="btnSend" x:Name="btnSend" FontSize="16" Content="提交" Width="100" Height="50" Margin="0,0,0,5" Command="{Binding DelegateCommand}"  ></Button></Grid>
</Window>

MainWindow.xaml.cs 文件

public partial class MainWindow : Window{public MainWindow(){InitializeComponent();this.DataContext = new SampleViewModel();}}

從上面的例子可以看出我們可以使用控件的Command屬性來綁定要執行的命令,我們還可以設置CommandParameter來傳遞參數,可以把UI上數據傳遞到后臺,WPF整個框架是基于數據驅動,我們可以做到把UI層完全剝離出來,所以說WPF是一個前端和后臺可以完全分離的框架。其實走到這里結合我們WPF-18 INotifyPropertyChanged 接口我們有點看到了MVVM開發模式的影子。

89caeb4767b8caf80770bc97bb0b4c3a.gif

接下來我們使用MVVM模式做一個簡單的Demo

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

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

相關文章

如何在Safari中查看網頁的完整URL

Modern versions of Safari don’t show the entire URL of a page in the address bar—it just shows the web site’s domain name. If this bothers you, it’s easy to change. Safari的現代版本無法在地址欄中顯示頁面的整個URL&#xff0c;而僅顯示網站的域名。 如果這困…

PHP | Uploading and reading of files and database 【PHP | 文件的上傳和讀取與數據庫】

這是我自己的一個作業&#xff0c;用的是很基礎的代碼。 有錯誤的地方歡迎批評和指正&#xff01; 這里最容易出錯的地方在讀取數據后向數據庫表中插入數據是的數據格式&#xff01; 文件上傳的頁面 uploading.php <html> <body align "center"> <fo…

Mqttnet內存與性能改進錄

1 MQTTnet介紹MQTTnet是一個高性能的 .NET MQTT庫&#xff0c;它提供MQTT客戶端和MQTT服務器的功能&#xff0c;支持到最新MQTT5協議版本&#xff0c;支持.Net Framework4.5.2版本或以上。MQTTnet is a high performance .NET library for MQTT based communication. It provid…

DataArtisans戰略聯手阿里云 Apache Flink服務能力云化

近日&#xff0c;Apache Flink商業公司 CEO、聯合創始人Kostas Tzoumas在云棲大會上宣布和阿里集團達成戰略合作伙伴關系&#xff0c;希望能夠借助全球最大的云計算公司之一阿里云&#xff0c;服務更多的大數據實時流計算的客戶。同時期待通過加強和阿里集團技術合作&#xff0…

高清、免版權美圖資源大全

正所謂“一圖勝千言”&#xff0c;當在寫文章、做設計、搞 PPT、發朋友圈&#xff0c;搭配一些合適的圖&#xff0c;這無疑將極大提升內容的表現力。鑒于此&#xff0c;在傾城之鏈的美圖板塊&#xff0c;收錄了來自世界各地的優質圖片網站&#xff0c;它們所提供高品質且免費的…

如何在WhatsApp中將群聊靜音

Group Chats are awesome if you’re in a club, want to keep in touch with all your friends, or are trying organize something. Unfortunately, if you’re busy and the other members decide to have a long, detailed conversation about the latest episode of Game …

Django進階之session

Django進階之session 基于cookie做用戶驗證時&#xff1a;敏感信息不適合放在cookie中 session依賴cookie session原理 cookie是保存在用戶瀏覽器端的鍵值對 session是保存在服務器端的鍵值對 session服務端中存在的數據為&#xff1a; session {隨機字符串1&#xff1a;{用戶…

Facebook開源 PyTorch版 fairseq,準確性最高、速度比循環神經網絡快9倍

今年5月&#xff0c;Facebook AI研究院&#xff08;FAIR&#xff09;發表了他們的研究成果fairseq&#xff0c;在fairseq中&#xff0c;他們使用了一種新型的卷積神經網絡來做語言翻譯&#xff0c;比循環神經網絡的速度快了9倍&#xff0c;而且準確性也是現有模型中最高的。此外…

推薦一個開源的現代化的 PDF 生成組件

你好&#xff0c;這里是 Dotnet 工具箱&#xff0c;定期分享 Dotnet 有趣&#xff0c;實用的工具和組件&#xff0c;希望對您有用&#xff01;前言QuestPDF 是一個開源免費的 .NET 組件庫&#xff0c;可以用來生成 PDF 文檔。在 Github 上有4千多的 Star。項目充分考慮了 PDF 文…

小程序調用阿里云身份證識別OCR(附帶七牛云上傳圖片)

寫在前面&#xff1a;實現的邏輯是拍照上傳調用后端封裝好的身份證接口&#xff0c;然后同時調用七牛云接口把照片傳過去以便后臺管理系統審核看1:首選需要這么一張頁面接下來就寫我是怎么做的首先是布局&#xff08;以下是wxml&#xff09; <view><view classidcard&…

windows 安裝yaml支持和pytest支持等

打開cmd 輸入pip install pyyaml #yaml文件支持 輸入pip install pytest #pytest框架支持 輸入pip install requests #requests接口測試支持 輸入pip install pyopenssl #openssl支持 前提是電腦上的python已經配置好了轉載于:https://www.cnblogs.com/mghhzAnne/p/92…

史上最好記的神經網絡結構速記表(上)

本文講的是史上最好記的神經網絡結構速記表&#xff08;上&#xff09;&#xff0c;新的神經網絡結構不斷涌現&#xff0c;我們很難一一掌握。哪怕一開始只是記住所有的簡稱&#xff08; DCIGN&#xff0c;BiLSTM&#xff0c;DCGAN &#xff09;&#xff0c;也會讓同學們吃不消…

厚積薄發,微軟OFFICE云時代宏腳本來臨,Excel Srcipt已經推進到桌面端可用

前一陣子&#xff0c;已經發現微軟在Excel上發布了Office Script For Excel&#xff0c;當時只能在網頁端的Excel上使用&#xff0c;今天打開桌面端的Excel&#xff0c;發現多了一個【自動執行】選項卡。再一次看了下&#xff0c;比起以前的Office Addin&#xff0c;要先進得多…

如何使用Amazon Echo控制您的Eero Wi-Fi網絡

Thanks to the power of Alexa and its open API, you’re able to control a vast number of devices using just your voice. If you have an Eero Wi-Fi system, you can even control your home network with the Amazon Echo. 得益于Alexa的強大功能及其開放的API&#xf…

H5在WebView上開發小結

背景 來自我司業務方要求&#xff0c;需開發一款APP。但由于時間限制&#xff0c;只能采取套殼app方式&#xff0c;即原生app內嵌webview展示前端頁面。本文主要記述JavaScript與原生app間通信&#xff0c;以及內嵌webview開發時&#xff0c;前端方面可能踩的一些坑。 技術架構…

C#的?和??

1.&#xff1f;&#xff1f; 為了實現Nullable數據類型轉換成non-Nullable類型數據&#xff0c;才有的一個操作符&#xff1b; 意義&#xff1a;一變量取值&#xff0c;取符號左邊的值&#xff0c;若左邊為null&#xff0c;那么取賦值&#xff1f;&#xff1f;右邊的&#xff1…

odoo 自定義視圖_如何使用Windows的五個模板自定義文件夾視圖

odoo 自定義視圖If you’re particular about how Windows displays the contents of your folders, you can cut your customization time down considerably by taking advantage of File Explorer’s five built-in folder templates. 如果您特別想知道Windows如何顯示文件夾…

C#之ILC和C++的CLR前者更快?

楔子ILC是C#寫的&#xff0c;CLR是C。.Net 7中&#xff0c;為何微軟執意用一個托管的模型去嘗試取代非托管框架呢&#xff1f;至少native code方面它是這么做的這個問題一直縈繞腦海。非托管和托管十年前出版的那本久負盛名的《CLR via C#》至今都是不可或缺的存在&#xff0c;…

歷史

python的歷史 kfsaldkfsdf fdskfdsa fdsjkafsjda fdshkfjsdja View Codefjdskaffdsjkaffdsjakflsad;fjdsklaf 轉載于:https://www.cnblogs.com/jin-xin/articles/10448286.html

typescript+react+antd基礎環境搭建

typescriptreactantd基礎環境搭建&#xff08;包含樣式定制&#xff09; tsconfig.json 配置 // 具體配置可以看上面的鏈接 這里module moduleResolution的配置都會影響到antd的顯示 // allowSyntheticDefaultImports 是antd官網給的配置 必須加上 {"compilerOptions&quo…