EventToCommand
在WPF中,並不是所有控件都有Command,例如TextBox,那么當文本改變,我們需要處理一些邏輯,這些邏輯在ViewModel
中,沒有Command如何綁定呢?這個時候我們就用到EventToCommand,事件轉命令,可以將一些事件例如TextChanged,Checked等
轉換成命令的方式。
不帶參數的EventToCommand
AppView.xaml
<CheckBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<command:EventToCommand Command="{Binding CheckedCommand}"></command:EventToCommand>
</i:EventTrigger>
<i:EventTrigger EventName="Unchecked">
<command:EventToCommand Command="{Binding UnCheckedCommand}"></command:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
AppViewModel.cs
public RelayCommand CheckedCommand
{
get;
set;
}
public RelayCommand UnCheckedCommand
{
get;
set;
}
public AppViewModel()
{
CheckedCommand = new RelayCommand(Checked);
UnCheckedCommand = new RelayCommand(UnChecked);
}
private void Checked()
{
MessageBox.Show("Checked");
}
private void UnChecked()
{
MessageBox.Show("Unchecked");
}
帶參數的EventToCommand
AppView.xaml
<Button Width="100" Height="30" Margin="0,100,0,0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<command:EventToCommand Command="{Binding ShowTxtCommand}" PassEventArgsToCommand="True" CommandParameter="Hello"></command:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
AppViewModel.cs
/// <summary>
/// 顯示消息命令
/// </summary>
public RelayCommand<string> ShowTxtCommand
{
get;
set;
}
public AppViewModel()
{
ShowTxtCommand=new RelayCommand<string>(ShowMsg);
}
/// <summary>
/// 命令具體實現
/// </summary>
private void ShowMsg(string msg)
{
MessageBox.Show(msg);
}
轉換傳遞的參數
也許你想知道事件是誰觸發的,從而進行一些業務邏輯,那么我們需要從IEventArgsConverter
繼承
EventArgsConverter.cs
public class EventArgsConverter : IEventArgsConverter
{
public object Convert(object value, object parameter)
{
var args = (RoutedEventArgs)value;
var btn = parameter as Button;
return btn.Name;
}
}
AppView.xaml
<Button Width="100" Height="30" Margin="0,100,0,0" x:Name="btn">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<command:EventToCommand Command="{Binding ShowNameCommand}" EventArgsConverter="{StaticResource ArgsConverter}" EventArgsConverterParameter="{Binding ElementName=btn}" PassEventArgsToCommand="True"></command:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
AppViewModel.cs
public RelayCommand<string> ShowNameCommand
{
get;
set;
}
public AppViewModel()
{
ShowNameCommand = new RelayCommand<string>(ShowName);
}
private void ShowName(string name)
{
MessageBox.Show(name);
}
看了EventToCommand的源碼,並沒有什么幫助,我猜測它的實現是這樣的,EventToCommand屬於附加
屬性,它就能獲取到它所附加的對象即控件本身,然后它還能Binding命令,比如我們附加的對象是Button
,那么就在它的Click事件時,觸發Command命令,同樣,有條件判斷Command是否能執行時,可以設置
控件的IsEnabled
屬性。