WPF禁用命令一段时间运行



我需要在运行的一段时间内禁用按钮。我有此代码:

relayCommand.cs 这是我的命令类。

class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
        {
            throw new ArgumentNullException("execute");
        }
        _execute = execute;
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

mainWindowViewModel.cs 这是我的绑定命令。

private RelayCommand _getTextCommand;
public ICommand GetTextCommand
{
    get
    {
        if (_getTextCommand == null)
        {
            _getTextCommand = new RelayCommand(
                param => this.GetText(param),
                param => true
                );
        }
        return _getTextCommand;
    }
}

mainwindow.xaml 这是XAML代码,我在其中绑定我的命令。

<Button x:Name="getTextButton" Command="{Binding GetTextCommand}" CommandParameter="{Binding ElementName=textTypeSelector, Path=SelectedIndex}"/>

这是我在命令中启动的代码:

public async void GetText(object o)
{
    await Task.Factory.StartNew(() =>
    {
        // code
    });
}

尝试以下操作:在视图模型中添加布尔属性并在视图模型中实现INotifyPropertyChanged

    private bool isEnable = true;
    public bool IsEnable 
    {
        get { return isEnable; }
        set
        {
            isEnable = value; 
            NotifyPropertyChanged();
        } 
    }
    public async void GetText(object o)
    {
        await Task.Factory.StartNew(() =>
        {
            IsEnable = false;
        });
        IsEnable = true;
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

将其绑定到按钮属性属性

<Button x:Name="abc"
                Command="{Binding GetTextCommand}"
                IsEnabled="{Binding IsEnable}" />

随时随地设置可安装。

向您的ViewModel添加布尔值,以指示命令正在执行并在您的getText()方法中设置布尔值。

private bool _isRunning = false;
public async void GetText(object o)
{
    await Task.Factory.StartNew(() =>
    {
        _isRunning = true;
        CommandManager.InvalidateRequerySuggested(); 
        // code
        _isRunning = false;
        CommandManager.InvalidateRequerySuggested();
    });
}
public bool CanGetText(object o){
  return ! _isRunning;
}

然后将您的继电器命令更改为以下

_getTextCommand = new RelayCommand(this.GetText,CanGetText);

问题是您正在为canexecute委托传递true。将其传递给每次需要评估时执行的方法,在该方法中,您可以测试以查看命令是否应执行或其他方式。

这是我正在使用的实现。它在ViewModel中不需要其他属性。

public sealed class AsyncDelegateCommand : ICommand
{
   private readonly Func<bool> _canExecute;
   private readonly Func<Task> _executeAsync;
   private Task _currentExecution;
   public AsyncDelegateCommand(Func<Task> executeAsync)
      : this(executeAsync, null)
   {
   }
   public AsyncDelegateCommand(Func<Task> executeAsync, Func<bool> canExecute)
   {
      if (executeAsync == null) throw new ArgumentNullException("executeAsync");
      _executeAsync = executeAsync;
      _canExecute = canExecute;
   }
   public event EventHandler CanExecuteChanged
   {
      add { CommandManager.RequerySuggested += value; }
      remove { CommandManager.RequerySuggested -= value; }
   }
   public bool CanExecute(object parameter)
   {
      if (_currentExecution != null && !_currentExecution.IsCompleted)
      {
         return false;
      }
      return _canExecute == null || _canExecute();
   }
   public async void Execute(object parameter)
   {
      try
      {
         _currentExecution = _executeAsync();
         await _currentExecution;
      }
      finally
      {
         _currentExecution = null;
         CommandManager.InvalidateRequerySuggested();
      }
   }
}

最新更新