Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
CommandRouting using a button.
Message
From
12/04/2008 04:46:49
 
 
To
12/04/2008 01:24:07
General information
Forum:
ASP.NET
Category:
Windows Presentation Foundation (WPF)
Miscellaneous
Thread ID:
01309791
Message ID:
01310153
Views:
12
This message has been marked as the solution to the initial question of the thread.
>>When I first tried your code my question was not why the windows level button didn't work - but why the ToolBar/MenuItem buttons *did*
>>Turns out the Toolbar and Menu have special functionality that automatically sets the CommandTarget to the control with focus. To get the windows button to fire the event in this scenario you need to set its CommandTarget property explicitly:
CommandTarget="{Binding ElementName=userControl}"
>
>I was aware of that but didn't use it because moving the bindings worked fine for my needs. It also only travels the tree from the point you bind it to up to the root and back so it won't change with the focus. But the way you worded that got me thinking and...
>
>Woot we have a solution:
>
>this.PreviewGotKeyboardFocus += new KeyboardFocusChangedEventHandler(Window1_PreviewGotKeyboardFocus);
>
>void Window1_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
>  {
>  Button2.CommandTarget = e.NewFocus;
>  }
>
>Now it works just like the toolbar or the menu. Thanks!

Hmm. Doesn't work for me because the buttons CommandTarget gets set to itself before the Command is actioned. So if the CommandBinding is added to the userControl all the buttons just get disabled. OTOH if the CommandBinding is added to the Windows collection it *appears* to work but actually with the wrong target. Apparently the true solution is to change the focus scope for the button. I don't know the detail of this but it certainly appears to work:
<Button x:Name="WindowBtn" FocusManager.IsFocusScope="true" Height="25" Command="ApplicationCommands.Save">Save</Button>
If you have other buttons needing the same mechanism then it makes sense to put them all into a container and set the focus scope on that. This is the same mechanism used by the Toolbar.
HTH,
Viv


>
>>BTW this info found in the Apress 'WPF in C#2008' which turned up today - looks good; certainly better coverage on Commands than from WPF Unleashed.
>>HTH,
>>Viv
>
>Cool once you get a better feel for them let me know which you like best. I have Applications = Code + Markup coming but the XAML purist crowd don't seem to like that one.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform