wpficommandcanexecute

WPF ICommand CanExecute get called even though there is a modal window


Let's say I have an user control with a button

<UserControl>
<Grid>
    <Button x:Name="button" Content="Show Dialog" DataContext="{Binding m_btnShowDialog}" Style="{StaticResource ButtonVM}" Command="{Binding Cmd}" HorizontalAlignment="Left" Margin="29,56,0,0" VerticalAlignment="Top" Width="75" >
</Grid>
</UserControl>

The command class implements ICommand interface.
When the focus is on the above dialog, the CanExecute sometimes get called.
That is something to be expected.

The problem is when I click the button, the Execute method get called and a new modal dialog pops up.
The focus should be on the new dialog but for some reasons, the CanExecute still get called when I interract with the new dialog.
Is that behavior normal?
And how can I override that behavior?
I don't want CanExecute method of commands attached to controls of parent dialog to be called when a child modal dialog is showing up.


Solution

  • This is expected. Quoting directly from WPF expert Josh Smith :

    WPF will automatically ask all of the commands being used in your UI if they can execute. This happens at various times, such as when input focus shifts to another control, an item is selected in a list, etc. You can also programmatically trigger this to happen by calling the CommandManager’s InvalidateRequerySuggested static method. This all seems magical, dreamy, and almost too good to be true.

    You can get more detailed and clear explanation here

    You can override behavior using CanExecuteChanged event in your command implementation.

    class MyCommand : ICommand
    {
    public bool CanExecute(object parameter)
    {
    return maybeTrueOrFalse;
    }
    
    public event EventHandler CanExecuteChanged
    {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
    }
    
    public void Execute(object parameter)
    {
    // Do something awesome.
    }
    }