在項目中使用Command綁定能夠使我們的代碼更加的符合MVVM模式。不了解的同學可能不清楚,只有繼承自ButtonBase類的元素才可以直接綁定Command(Button、CheckBox、RadioButton等)
<Button Content="Normal" Command="{Binding NormalEventCommand}" ></Button>
如果我們要處理Label或者其他的一些控件,那么只能在走事件:
<Label Content="Label Event" MouseDoubleClick="Label_MouseDoubleClick_1"></Label>
這樣的話,我們不得不在窗體類中處理事件代碼和部分邏輯,這樣就無法得到干凈的MVVM模式了,那么我們應該怎么做呢?
Blend為我們提供了解決方案,我們安裝Blend以后,便可以獲取到System.Windows.Interactivity.dll,添加該dll到項目引用
<Window x:Class="WpfApplication1.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:vm="clr-namespace:WpfApplication1" Title="Window2" Height="124" Width="214"> <Window.DataContext> <vm:Window2ViewModel /> </Window.DataContext> <Grid> <Button Name="btn" Content="Button" Height="33" HorizontalAlignment="Left" Margin="40,24,0,0" VerticalAlignment="Top" Width="109"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:InvokeCommandAction Command="{Binding Command1}" CommandParameter="10" /> </i:EventTrigger> <i:EventTrigger EventName="MouseMove"> <i:InvokeCommandAction Command="{Binding Command2}" CommandParameter="{Binding ElementName=btn}" /> </i:EventTrigger> </i:Interaction.Triggers> </Button> </Grid> </Window>
需要注意Window標簽中的
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity",這里相當於后台的using System;之類的加載程序集的功能
這樣的我們,我們便可以處理所有目標元素的事件。
同樣我們面對另外一個問題,我們是否可以綁定按鍵事件,並處理特定的鍵值命令呢?答案是肯定的,使用KeyBinding就可以了,同樣還可以使用MouseBinding進行鼠標事件的處理。
<TextBox Text="test"> <TextBox.InputBindings> <KeyBinding Key="S" Modifiers="Alt" Command="{Binding KeyEventCommand}"></KeyBinding> <MouseBinding Gesture="RightClick" MouseAction="LeftClick" Command="{Binding MouseEventCommand}"></MouseBinding> </TextBox.InputBindings> </TextBox> <Label Content="test"> <Label.InputBindings> <KeyBinding Key="S" Modifiers="Alt" Command="{Binding KeyEventCommand}"></KeyBinding> <MouseBinding MouseAction="LeftClick" Command="{Binding MouseEventCommand}"></MouseBinding> </Label.InputBindings> </Label>
這里我們針對TextBox和Label進行了InputBindings的綁定。
需要注意的是:
1.InputBindings是個綁定集合InputBindingCollection,可以有多個MouseBinding和多個KeyBinding
2.KeyBinding綁定對象需要可聚焦,這里的Label由於無法聚焦,所以無法響應Alt+S事件
3.MouseBinding中Gesture的優先級高於MouseAction,當Gesture設置以后,LeftClick將失效