以下两个元素在我的 ICommand 实现中以不同方式触发并导致问题。当实现为TextBox输入CanExecuteChanged(object parameter)时,parameter的值为null。当它为Button输入相同的方法时,参数的值等于CommandParameter。
理想情况下,我希望在这两种情况下,CommandParameter 值都不会发送到 CanExecuteChanged,而只会发送到 Execute。
ICommand的实现
public event EventHandler CanExecuteChanged
{
add
{
canExecuteChanged += value;
CommandManager.RequerySuggested += value;
}
remove
{
canExecuteChanged -= value;
CommandManager.RequerySuggested -= value;
}
}
public bool CanExecute(object parameter)
{
if (parameter is bool)
{
this.canExecute = (bool)parameter;
}
return this.canExecute;
}
public void Execute(object parameter)
{
this.executeAction((T)parameter);
}
internal void RaiseCanExecuteChanged()
{
this.OnCanExecuteChanged();
}
private void OnCanExecuteChanged()
{
if (this.canExecuteChanged != null)
{
this.canExecuteChanged(this, EventArgs.Empty);
}
}
文本框
<TextBox Width="80" Margin="2,2,2,2" Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}" MaxLength="25">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding SearchCommand}">
<KeyBinding.CommandParameter>
<s:Boolean>True</s:Boolean>
</KeyBinding.CommandParameter>
</KeyBinding>
</TextBox.InputBindings>
</TextBox>
按钮
<Button Margin="2,2,2,2" Padding="10,0,10,0" Content="Search">
<Button.InputBindings>
<MouseBinding Command="{Binding SearchCommand }" MouseAction="LeftClick">
<MouseBinding.CommandParameter>
<s:Boolean>True</s:Boolean>
</MouseBinding.CommandParameter>
</MouseBinding>
</Button.InputBindings>
</Button>