WPF MVVM Переключатель включен / отключен во время выполнения - PullRequest
0 голосов
/ 23 января 2019

Я бы хотел отключить кнопку и активировать ее во время выполнения, когда другой метод устанавливает для поля _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 голосов
/ 23 января 2019

Вы можете добавить такой метод в ваш класс CommandHandler:

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

Затем изменить тип свойства ClickCommand на CommandHandler

public CommandHandler ClickCommand => ...

и просто вызвать

ClickCommand.SetCanExecute(true);
...