如何以编程方式引发CanExecuteChanged()?

时间:2018-12-27 00:17:46

标签: c# mvvm

我需要以编程方式提高CanExecuteChanged()ICommand类如下所示:

public class PlayCommand : ICommand
{
    private readonly TpViewModel _tpViewModel;
    private bool IsBusy;

    public PlayCommand(TpViewModel tpViewModel)
    {
        _tpViewModel = tpViewModel;
    }

    public bool CanExecute(object parameter)
    {
        return !IsBusy;
    }

    public async void Execute(object parameter)
    {
        if (IsBusy)
            return;

        await Play();
    }

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }

    private async Task Play()
    {
        IsBusy = true;

        Console.WriteLine("Play")

        IsBusy = false;
    }
}

Play方法完成后,应立即启用Play()按钮。但是,启用该按钮似乎要延迟一两秒钟。

我尝试过CommandManager.InvalidateRequerySuggested(),但是它不起作用。

1 个答案:

答案 0 :(得分:2)

您可以使用CommandManager.InvalidateRequerySuggested(),尽管这很昂贵。但是,您可以仅使用标准事件模式来扩展类。

注意 :这仅是基于您的代码的示例,并非旨在成为世界上最好的ICommand实现,根据需要对其进行修改

private EventHandler _canExecuteChanged;

public event EventHandler CanExecuteChanged
{
   add
   {
      _canExecuteChanged += value;
      CommandManager.RequerySuggested += value;
   }
   remove
   {
      _canExecuteChanged -= value;
      CommandManager.RequerySuggested -= value;
   }
}

public void RaiseCanExecuteChanged()
{
   if (!IsBusy)
      OnCanExecuteChanged();
}

protected virtual void OnCanExecuteChanged()
   => _canExecuteChanged?.Invoke(this, EventArgs.Empty);