When is CanExecute called?

前端 未结 4 1994
离开以前
离开以前 2020-11-29 10:41

In the demo, I have a button to toggle a bool field isAsking. I create a command which can execute only when isAsking==true.

Once I press T

4条回答
  •  独厮守ぢ
    2020-11-29 11:46

    RoutedCommand contains an event CanExecuteChanged which internally hook to the CommandManager.RequerySuggested event -

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

    And CommandManager.RequerySuggested event is raised

    whenever changes to the command source are detected by the command manager which is in your case is Window. So, when button is clicked, commandManager raised the RequerySuggested event and hence executed the CanExecute predicate registered for your command.

    Also, CommandManager has a static method - InvalidateRequerySuggested which forces the CommandManager to raise the RequerySuggestedEvent. So, you can call that to validate your commands too manually.

提交回复
热议问题