【问题标题】:WPF MVVM Toggle button enabled/disabled during runtimeWPF MVVM 切换按钮在运行时启用/禁用
【发布时间】: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


【解决方案1】:

您可以在您的 CommandHandler 类中添加这样的方法:

public void SetCanExecute(bool canExecute)
{
    _canExecute = canExecute;
    RaiseCanExecuteChanged();
}

然后将ClickCommand属性的类型改为CommandHandler

public CommandHandler ClickCommand => ...

然后打电话

ClickCommand.SetCanExecute(true);

【讨论】:

  • 完美!期望得到满足。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-11-23
  • 2020-09-12
  • 2013-07-03
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
  • 2015-04-19
  • 2019-02-01
相关资源
最近更新 更多