Search code examples
c#wpfbuttonmvvmicommand

WPF MVVM Toggle button enabled/disabled during runtime


I would like to set a button to disabled and activate it at runtime when another method sets the _canExecute field to true. Unfortunately I don't know how to trigger this event and update the view. The CommandHandler class already implements RaiseCanExecuteChanged. But it's unclear how to use it.

View

<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());
        }


    }

Solution

  • You may add a method like this to your CommandHandler class:

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

    Then change the type of the ClickCommand property to CommandHandler

    public CommandHandler ClickCommand => ...
    

    and just call

    ClickCommand.SetCanExecute(true);