Geeks With Blogs


Add to Google

Tim Hibbard CEO for EnGraph software

In WPF, access keys are created like this:
_Click Me!

Pre-WPF was:
&Click Me!

Access keys in buttons work differently based on the type of control your text is rendered in.

This code will only bring the keyboard focus to the button, it will not generate a click event:

<Button Click="clickMeClick">_Click Me!</Button>

When the user presses Alt - C on their keyboard, they expect the button to act as if it has been clicked, not just selected.

To set keyboard focus and generate a click event, use code like this:

<Button Click="clickMeClick"> <Label>_Click Me!</Label> </Button>

I *think* the default content of a button is a TextBlock, so until we explicitly set a Label inside of it, the button does not work with access keys as expected.  For other differences between a TextBlock and Label, see Josh Smith's post.


To use access keys to attach a label to another control, use code like this:

<DockPanel LastChildFill="True"> <Label Width="100" DockPanel.Dock="Left" Target="{Binding ElementName=firstNameText}">_First Name</Label> <TextBox Name="firstNameText"/> </DockPanel>

Now, when the user presses Alt - F on their keyboard, the TextBox will receive keyboard focus.


Technorati tags: , ,
Posted on Tuesday, August 28, 2007 10:15 AM .NET , Keyboard Shortcuts , WPF | Back to top

Comments on this post: WPF Access Keys

# re: WPF Access Keys
Requesting Gravatar...
I'm using a button binded to a command and when I press Alt-N, my button act as clicked and the command is executed.
Left by Danilo da Silva on May 14, 2013 5:30 PM

Your comment:
 (will show your gravatar)

Copyright © Tim Hibbard | Powered by: