【发布时间】:2019-01-22 15:36:08
【问题描述】:
我有三个与同一命令关联的按钮:
<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;
}
}
【问题讨论】:
-
最简单的方法是将命令参数传递给命令。看看这个线程是如何完成的。 stackoverflow.com/questions/32064308/…
-
另外,就其价值而言,您的 Command 对象不应该知道有关哪个控件调用该命令的任何信息。这就是首先拥有一个 Command 对象的全部意义所在。