WPF Label, TextBox, and Mnemonics

Hello. Today I had to get mnemonic to work. Mnemonic is the ability to navigate to a control using a key stroke combination. One of the most common mnemonics is Alt + F. Alt + F usually navigates to the File drop down menu in any Window, and most everyone is familiar with this mnemonic.

In WPF, to get mnemonics, you pretty much just put an underscore in front of a word. For example, for Alt + F, you would enter: _File

Well, in WPF I needed to do the Label, TextBox matching, so that the mnemonics is on a Label but the key strokes navigate the keyboard focus to the TextBox.

Lets say you have a simple form in WPF like this:

The XAML to make these work together using mnemonics is simple. The important property is Target.

<Window x:Class="Mnemonics.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" >
    <Grid FocusManager.FocusedElement="{Binding ElementName=textBoxFirstName}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Label Target="{Binding ElementName=textBoxFirstName}" HorizontalContentAlignment="Right">
            <AccessText TextWrapping="WrapWithOverflow">First _Name:</AccessText>
        </Label>
        <TextBox Name="textBoxFirstName" Width="200" Height="20" Grid.Column="1"/>
        <Label Target="{Binding ElementName=textBoxLastName}" HorizontalContentAlignment="Right" Grid.Row="1">
            <AccessText TextWrapping="WrapWithOverflow">_Last Name:</AccessText>
        </Label>
        <TextBox Name="textBoxLastName" Width="200" Height="20" Grid.Row="1" Grid.Column="1"/>
    </Grid>
</Window>

Lets discuss the code above briefly.

  1. Notice line 5 first.  Here I am setting the FocusManager.FocusedElement to the first text box so that you can immediately type in the first field when arriving at the window.
  2. Notice the use of AccessText instead of TextBlock (lines 15, 19).  You don’t have to do it this way.  You could have just set the Content property on the label. You don’t need the AccessText at all unless you want to wrap.  If you want to wrap, you have to do it this way.
  3. Notice the use of Target (lines 18,14) and how it is bound to the element that should receive focus when the mnemonic keys are pressed.

Hope this helps you.

Leave a Reply