WPF MVVM 运行时切换按钮 enabled/disabled
WPF MVVM Toggle button enabled/disabled during runtime
我想将一个按钮设置为禁用,并在运行时当另一个方法将 _canExecute 字段设置为 true 时将其激活。
不幸的是,我不知道如何触发此事件并更新视图。
CommandHandler class 已经实现了 RaiseCanExecuteChanged。但是不清楚怎么用。
查看
<Button Content="Button" Command="{Binding ClickCommand}" />
ViewModel
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());
}
}
您可以将这样的方法添加到您的 CommandHandler class:
public void SetCanExecute(bool canExecute)
{
_canExecute = canExecute;
RaiseCanExecuteChanged();
}
然后将 ClickCommand 的类型 属性 更改为 CommandHandler
public CommandHandler ClickCommand => ...
然后打电话
ClickCommand.SetCanExecute(true);
我想将一个按钮设置为禁用,并在运行时当另一个方法将 _canExecute 字段设置为 true 时将其激活。 不幸的是,我不知道如何触发此事件并更新视图。 CommandHandler class 已经实现了 RaiseCanExecuteChanged。但是不清楚怎么用。
查看
<Button Content="Button" Command="{Binding ClickCommand}" />
ViewModel
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());
}
}
您可以将这样的方法添加到您的 CommandHandler class:
public void SetCanExecute(bool canExecute)
{
_canExecute = canExecute;
RaiseCanExecuteChanged();
}
然后将 ClickCommand 的类型 属性 更改为 CommandHandler
public CommandHandler ClickCommand => ...
然后打电话
ClickCommand.SetCanExecute(true);