【发布时间】:2017-07-24 07:05:00
【问题描述】:
继续沿着 MVVM 的路径前进,我来到了按钮命令。经过相当多的反复试验,我终于有了一个使用ICommand 的Button_Click 命令的工作示例。
我的问题是,现在我制作了一个通用事件,我无法获取单击了哪个按钮来对其应用一些逻辑。在我的示例中,我没有使用任何可以获取 Sender 信息的东西。通常像下面这样使用RoutedEventArgs:
Button button = (Button)sender;
这就是我目前所拥有的。
ICommand 类:
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
以及执行操作的代码:
private ICommand _clickCommand;
public ICommand ClickCommand => _clickCommand ?? (_clickCommand = new CommandHandler(MyAction, _canExecute));
public ViewModelBase()
{
_canExecute = true;
}
public void MyAction()
{
//Apply logic here to differentiate each button
}
还有 XAML,
<Button Command="{Binding ClickCommand}" Style="{StaticResource RedButtonStyle}">MyButton</Button>
当将相同的命令绑定到其他按钮时,我将如何识别正在单击的按钮?
【问题讨论】:
-
只是好奇,为什么不直接使用 2 ICommands?
-
@XanderLuciano,我只是认为应用一些标准来区分方法中的按钮是这样做的方法。干杯
-
很公平!大约一个月前我刚刚开始使用 MVVM,所以我理解必须调整你的想法的困难。祝你好运!
-
@XanderLuciano,感谢您的支持,干杯。