Search code examples
c#.netwpfcommand

WPF: Command Is Disabled


I have a WPF UserControl, which contains a toolbar with 5 buttons. The commands for 4 of the buttons is handled in the parent window, but the fifth button's command is handled by the UC itself. It seems no matter what I try, the button is always disabled. This is my code:

In the user control...

<UserControl.CommandBindings>
<CommandBinding Command="loc:MyAppCommands.OpenUrl" Executed="OpenUrl" />
</UserControl.CommandBindings>

The button in question...

<l49ui:ImageButton 
  Command="loc:MyAppCommands.OpenUrl" 
  CommandParameter="{Binding}" 
  Text="{lex:LocText MyApp.Core:Strings:OpenUrl}"  
  ShowText="False" 
  ToolTip="{lex:LocText MyApp.Core:Strings:OpenUrl}" 
  Style="{StaticResource ToolBarButton}" 
  Image="{Binding Url,Converter={StaticResource UrlNotNullConverter},ConverterParameter=image}" 
  IsEnabled="true" /> 

The datacoontext for the user control is set based on a list selection; so I have WIndow->UserControl tied to ListBox->TabControl->Toolbar buttons

The image changes based on whether the commandparameter (Url in this case) is empty, and this works. However, the button is always disabled. The only thing which causes it to enable is switching to another tab in a pareent tab control, then back to to tab with the button.

I've tried calling CommandManager.InvalidateRequerySuggested(); when the datacontext changes and adding a "CanAlwaysExecute" handler for the command, but the CanExecute handler isn't executed when I call CommandManager.InvalidateRequerySuggested();.


Solution

  • It might be an issue with focus scopes. Try specifying the CommandTarget property explicitly on your button. Set it to an element inside your user control on which the Execute and CanExecute events should be raised (probably root element inside the user control).