WPF - How to force a Command to re-evaluate 'CanExecute' via its CommandBindings

前端 未结 6 1253
礼貌的吻别
礼貌的吻别 2020-11-29 17:47

I have a Menu where each MenuItem in the hierarchy has its Command property set to a RoutedCommand I\'ve defined. The as

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 17:56

    I couldnt use CommandManager.InvalidateRequerySuggested(); because I was getting performance hit.

    I have used MVVM Helper's Delegating command, which looks like below (i have tweaked it a bit for our req). you have to call command.RaiseCanExecuteChanged() from VM

    public event EventHandler CanExecuteChanged
    {
        add
        {
            _internalCanExecuteChanged += value;
            CommandManager.RequerySuggested += value;
        }
        remove
        {
            _internalCanExecuteChanged -= value;
            CommandManager.RequerySuggested -= value;
        }
    }
    
    /// 
    /// This method can be used to raise the CanExecuteChanged handler.
    /// This will force WPF to re-query the status of this command directly.
    /// 
    public void RaiseCanExecuteChanged()
    {
        if (canExecute != null)
            OnCanExecuteChanged();
    }
    
    /// 
    /// This method is used to walk the delegate chain and well WPF that
    /// our command execution status has changed.
    /// 
    protected virtual void OnCanExecuteChanged()
    {
        EventHandler eCanExecuteChanged = _internalCanExecuteChanged;
        if (eCanExecuteChanged != null)
            eCanExecuteChanged(this, EventArgs.Empty);
    }
    

提交回复
热议问题