0

I have a WPF usercontrol, which contains a toolbar with 5 buttons. The commands for for 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();.

Echilon
  • 10,064
  • 33
  • 131
  • 217

2 Answers2

4

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).

dotNET
  • 33,414
  • 24
  • 162
  • 251
Pavlo Glazkov
  • 20,498
  • 3
  • 58
  • 71
  • Thanks, Commands have always been a bit of a murky area of understanding for me. – Echilon Apr 03 '11 at 17:39
  • 4
    Is this intended behaviour or a bug? I am starting to wonder whether WPF is really worth it; it does lots of complicated things, but almost everything that used to be simple or Just Worked in WinForms, is sacrificed in WPF to get those complex things to work. – Roman Starkov Mar 26 '12 at 17:05
  • @romkyns - Well, if I remember correctly, it is intended behavior. For example, see the following answer for some information on how focus scopes work: http://stackoverflow.com/questions/4954253/strange-focus-behavior-for-simple-wpf-itemscontrol. – Pavlo Glazkov Mar 28 '12 at 07:06
0

Are you maybe handling the CanExecute event for this command in a parent control? If the event bubbles up the tree, maybe in another place it is handled with a 'false' return value, so the button is disabled. I'd try to handle the CanExecute event within the UserControl, and set a breakpoint there to investigate further.

Haplo
  • 1,368
  • 9
  • 18