Search code examples
c#wpfcommandrouted-commands

RegisterClassCommandBinding not firing CanExecute


In certain situations (I couldn't establish a pattern) the execution goes over

    System.Windows.Input.CommandManager.InvalidateRequerySuggested();
    var can = GlobalCommands.UpdateWindowTitle.CanExecute(title, null);
    GlobalCommands.UpdateWindowTitle.Execute(title, null);

without entering CanExecute nor Execute methods. Variable "can" is false (without executing CanExecute), and the command never fires. But sometimes it works as expected.

This is how the command is created and bound:

    var updateTitleBinding = new CommandBinding(GlobalCommands.UpdateWindowTitle,         UpdateWindowTitle, CanUpdateWindowTitle);
    CommandManager.RegisterClassCommandBinding(typeof(System.Windows.Window), updateTitleBinding);

I can't use

    Application.Current.MainWindow.CommandBindings.Add(
         new CommandBinding(_addCommand, ExecuteAddCommand, CanExecuteAddCommand));

because the calling class is not a visual element and doesn't have CommandBindings

I tried calling

    System.Windows.Input.CommandManager.InvalidateRequerySuggested();

before CanExecute and Execute calls, but this doesn't affect the behaviour.

--

Do you know what might be happening there? Are there any other patterns that I could use?

The problem looks similar to CanExecute method going to false problem but I'm not setting focus anywhere.

Thanks!


Solution

  • Well since you're passing in null for the target that would mean the framework will route based on the Keyboard.FocusedElement so either that is null (which can happen if the application isn't active or keyboard focus is within something else like an HwndHost or MessageBox) or the Keyboard.FocusedElement is non-null but not within the visual/logicaltree of a Window.