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.html1 <TextBlock>
2 <i:Interaction.Triggers>
3 <i:EventTrigger EventName="MouseLeftButtonDown">
4 <i:InvokeCommandAction Command="{Binding MouseLeftButtonDownCommand}"/>
5 </i:EventTrigger>
6 </i:Interaction.Triggers>
7 </TextBlock>
快捷鍵綁定
通過Key值,綁定ViewModel中相應指令
1 <UserControl.InputBindings>
2 <KeyBinding Key="Delete" Command="{Binding MenuDeleteCommand}" />
3 </UserControl.InputBindings>
作者:
唐宋元明清2188出處:
http://www.cnblogs.com/kybs0/本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文連接配接,否則保留追究法律責任的權利。