WPF MVVM切换按钮在运行时启用/禁用

时间:2019-01-23 09:30:48

标签: c# wpf button mvvm icommand

当另一个方法将_canExecute字段设置为true时,我想将按钮设置为禁用并在运行时激活它。 不幸的是,我不知道如何触发该事件和更新视图。 CommandHandler类已实现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());
        }


    }

1 个答案:

答案 0 :(得分:1)

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

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

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

public CommandHandler ClickCommand => ...

然后打电话

ClickCommand.SetCanExecute(true);