Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make custom MenuHeaders in WPF with accelerators?

I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.

Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, _File

However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?

<Menu>
<MenuItem>
    <MenuItem.Header>
    <UserControl>
        <Image Source="..." />
        <Label Text="_Open" />
    </UserControl>
    </MenuItem.Header>
</MenuItem>
...
like image 309
Nidonocu Avatar asked Dec 14 '22 06:12

Nidonocu


2 Answers

I think the Icon property fits your needs.
However to answer the original question, it is possible to retain the Accelerator functionality when you compose the content of your menuitem. If you have nested content in a MenuItem you need to define the AccessText property explicitly like in the first one below. When you use the inline form, this is automagically taken care of.

 <Menu> 
   <MenuItem>
      <MenuItem.Header>
        <StackPanel Orientation="Horizontal">
          <Image Source="Images/Open.ico" />      
          <AccessText>_Open..</AccessText>
        </StackPanel>
      </MenuItem.Header>
    </MenuItem>
    <MenuItem Header="_Close" />
   </Menu>
like image 142
Gishu Avatar answered Dec 16 '22 18:12

Gishu


The problem is you placed the image inside of the content of the MenuHeader which means that you'll lose the accelerator key. If you're just trying to have an image in the menu header, do the following.

<MenuItem Header="_Open">
  <MenuItem.Icon>
    <Image Source="images/Open.png"/>
  </MenuItem.Icon>
</MenuItem>

If you want to customize the look and feel even further, modify the controltemplate and style for the menu. From experience, styling the menus and menuitems are much more difficult then styling the other WPF controls.

like image 35
Alan Le Avatar answered Dec 16 '22 17:12

Alan Le