WPF 界面如何綁定Command


WPF中,我們使用MVVM,在ViewModel中定義Command和其業務邏輯,界面綁定Command。

那么是不是所有的事件都可以定義Command呢,然后將業務全部放在ViewModel中呢?

界面CommandBindings

如果只是交互的處理,可以直接定義RoutedCommand即可

1. 添加Command

1 <RoutedCommand x:Key="SelectAllCommand"/> 

2. 添加命令委托處理

1 <UserControl.CommandBindings>
2     <CommandBinding Command="{StaticResource  SelectAllCommand}" Executed="SelectAllExecuted"/>
3 </UserControl.CommandBindings>

3. 綁定Command

1 <CheckBox Name="AllSelectCheckBox" Command="{StaticResource SelectAllCommand}" />

 

InvokeCommandAction

控件不只有Button,還有其它很多TextBox/ListBox等控件甚至自定義控件的KeyDown/MouseUp/LostFocus等事件以及自定義的事件。

我們都知道Buttton有Command屬性(對應Click事件),直接綁定相應的Command就可以了,那么除Button.Click事件之外的事件怎么綁定?

CommandAction是Trigger與Command的中間轉換器

通過InvokeCommandAction 的使用,WPF任意事件都可以綁定Command,將業務邏輯放在ViewModel中。如:

自定義Command,請參考https://www.cnblogs.com/kybs0/p/7523654.html

案例:下載 System.Windows.Interactivity.dll,引用后就可以直接使用如下的Interaction了。

1     <Button x:Name="SearchingButton">
2         <i:Interaction.Triggers>
3             <i:EventTrigger EventName="MouseDown">
4                 <i:InvokeCommandAction Command="{Binding SearchCommand}" 
5                                         CommandParameter="{Binding ElementName=SearchingTextBox,Path=Text}"/>
6             </i:EventTrigger>
7         </i:Interaction.Triggers>
8     </Button>

 

 快捷鍵綁定

通過Key值,綁定ViewModel中相應命令

1 <UserControl.InputBindings>
2     <KeyBinding Key="Delete" Command="{Binding MenuDeleteCommand}" />
3 </UserControl.InputBindings>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM