Frage

I've got next makrup:

<Style TargetType="{x:Type MenuItem}">
<Setter Property="MinWidth" Value="65" />
<Setter Property="MinHeight" Value="30" />
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type MenuItem}">
            <Border x:Name="MainBorder" BorderThickness="1" Background="Black">                 
                <TextBlock Margin="5" Text="{TemplateBinding Header}" Foreground="{TemplateBinding Foreground}" />

                <Popup x:Name="SubMenuPopup" IsOpen="{Binding Path=IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" Placement="Right"
                            AllowsTransparency="True" Focusable="False">
                    <Border Background="Gray">
                        <Grid x:Name="SubMenu" Grid.IsSharedSizeScope="True" Background="Transparent">
                            <StackPanel Margin="0" IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle" Background="Gray" />
                        </Grid>
                    </Border>
                </Popup>
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

When I create MenuItem somewhere and set it's Header property with "_" symbol - it doesn't create shortcut for this menu item. Example - letter 'F' is not underlined and shortcut doesn't work.

How to support shortcuts in ControlTemplates in MenuItems?

Thanks.

War es hilfreich?

Lösung

It is not the complete template but instead of the TextBlock put a ContentPresenter that can recognize access keys:

<ContentPresenter Margin="5" Content="{TemplateBinding Header}" TextBlock.Foreground="{TemplateBinding Foreground}" RecognizesAccessKey="True" />

I suppose the xaml you have pasted here is only part of your implementation, so my solution is onl y a continuation of yours with the access key working...

You can find entire templates just like this one: http://msdn.microsoft.com/en-us/library/ms747082%28v=vs.85%29.aspx

Andere Tipps

If you want you menu item letter to underline itself of keypress then you have to set the InputGesture on menuitem like this:

      <MenuItem Header="_File" 
          InputGestureText="Ctrl+F"
          Commmand={Binding NewFileCommand}/>

But if you want to create shortcut for the menuitem command then you will have to create the commandbindings like below on your window:

      <Window.CommandBindings>
                <CommandBinding Command="local:MyCommands.NewFile" Executed="NewFile_Executed" />
        </Window.CommandBindings>
        <Window.InputBindings>
                <KeyBinding Key="F" Modifiers="Control" Command="local:MyCommands.NewFile"/>
        </Window.InputBindings>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top