我有三个与同一命令关联的按钮:
<StackPanel>
<Button Name="Btn1" Content="Test 1" Command="{Binding CmdDoSomething}" />
<Button Name="Btn2" Content="Test 2" Command="{Binding CmdDoSomething}" />
<Button Name="Btn3" Content="Test 3" Command="{Binding CmdDoSomething}" />
</StackPanel>
如何知道哪个Button调用了命令或将该信息传递给方法调用?
CmdDoSomething = new DelegateCommand(
x => DvPat(),
y => true
);
这是我的DelegateCommand类:
public class DelegateCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
private readonly Predicate<object> _canExecute;
public bool CanExecute(object parameter) => _canExecute == null ? true : _canExecute(parameter);
private readonly Action<object> _execute;
public void Execute(object parameter) => _execute(parameter);
public DelegateCommand(Action<object> execute) : this(execute, null) { }
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
}
答案 0 :(得分:3)
Commands paradigm和DelegateCommand
包含参数,您可以将其传递给具有CommandParameter
属性的处理程序并在处理程序中使用它:
<StackPanel>
<Button Name="Btn1" Content="Test 1" Command="{Binding CmdDoSomething}" CommandParameter="Test 1" />
<Button Name="Btn2" Content="Test 2" Command="{Binding CmdDoSomething}" CommandParameter="Test 2" />
<Button Name="Btn3" Content="Test 3" Command="{Binding CmdDoSomething}" CommandParameter="Test 3" />
</StackPanel>
CmdDoSomething = new DelegateCommand(
parameter => DvPat(parameter),
y => true
);
此参数还可用于在调用CanExecute(object param)
时评估命令的状态。