【发布时间】:2019-06-16 20:27:03
【问题描述】:
我想将一个按钮设置为禁用,并在运行时在另一个方法将 _canExecute 字段设置为 true 时激活它。 不幸的是,我不知道如何触发此事件并更新视图。 CommandHandler 类已经实现了 RaiseCanExecuteChanged。但是具体怎么用还不清楚。
查看
<Button Content="Button" Command="{Binding ClickCommand}" />
视图模型
public ViewModel(){
_canExecute = false;
}
private bool _canExecute;
private ICommand _clickCommand;
public ICommand ClickCommand => _clickCommand ?? (_clickCommand = new CommandHandler(MyAction, _canExecute));
private void MyAction()
{
// Do something after pressing the button
}
private void SomeOtherAction(){
// If all expectations are satisfied, the button should be enabled.
// But how does it trigger the View to update!?
_canExecute = true;
}
CommandHandler
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();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, new EventArgs());
}
}
【问题讨论】:
-
只需更新命令的
_canExecute字段并调用其RaiseCanExecuteChanged()方法。 -
如果你实现了 INotifyPropertyChanged,你可以改为将按钮的 IsEnabledProperty 绑定到 ViewModel 中的属性
-
@DanieleSartori 出于什么原因? ICommand 已经支持禁用控件。不需要其他机制。
-
@Clemens:不确定在哪里/如何触发 RaiseCanExecuteChanged。
标签: c# wpf button mvvm icommand