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

前端 未结 6 1236
礼貌的吻别
礼貌的吻别 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 18:05

    If you have rolled your own class that implements ICommand you can lose a lot of the automatic status updates forcing you to rely on manual refreshing more than should be needed. It can also break InvalidateRequerySuggested(). The problem is that a simple ICommand implementation fails to link the new command to the CommandManager.

    The solution is to use the following:

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    
        public void RaiseCanExecuteChanged()
        {
            CommandManager.InvalidateRequerySuggested();
        }
    

    This way subscribers attach to CommandManager rather than your class and can properly participate in command status changes.

提交回复
热议问题