c# - 如何判断哪个 WPF 控件调用了命令?
问题描述
我有三个与同一命令关联的按钮:
<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;
}
}
解决方案
命令范例和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)
调用时的状态。
推荐阅读
- ios - 在 iPhone 上运行项目崩溃,但它可以在模拟器上运行
- nuget - 无法安装 GoogleAnalyticsTracker.Core Nuget 包
- android - 如何制作fab center cut android studio
- r - R:循环遍历一个数据帧中的一组值更新第二个数据帧
- node.js - 当我向 babel.config.js 添加忽略选项时,Babel-node 忽略或行为不端
- python - 如何在单独的数字上绘制 Pandas Dataframe 列?
- windows - 如何在 FFmpeg 上使用带有电影过滤器的 Windows 绝对路径?
- ffmpeg - 来自图像文件的 FFMPEG 视频循环
- python - 移动游戏背景不重绘本身
- javascript - 在运行时使用参数更改 nodejs 路由