MIcheal David
MIcheal David

Reputation: 149

Styling a Button with MenuItems WPF

Please i need a way to come up with a style like these styled Image

But this is the current one i'm using Unstyled Image

Please if you can help out with maybe a Link, Code, Tutorial on how to get it done, i'll greatly appreciate. Thanks..

Upvotes: 0

Views: 1006

Answers (1)

Modifying the styles of a MenuItem (WPF) is more complicated than it might seem, because the same MenuItem control uses different templates depending on the Role assigned to each MenuItem: SubmenuItem, TopLevelHeader and SubmenuHeader. With the menu bar you should not have any problem: if you want, you can define your style and your template as with any other control. For MenuItem, try something like this:

<ControlTemplate x:Key="{x:Static MenuItem.SubmenuItemTemplateKey}" TargetType="{x:Type local:MyMmenuItem}">  
...
</ControlTemplate>
<ControlTemplate x:Key="{x:Static MenuItem.TopLevelHeaderTemplateKey}" TargetType="{x:Type local:MyMenuItem}">
...
</ControlTemplate>
<ControlTemplate x:Key="{x:Static MenuItem.SubmenuHeaderTemplateKey}" TargetType="{x:Type local:MyMenuItem}">
...
</ControlTemplate>

And to switch between different templates, we will use the RoleProperty dependency property, defining these triggers in our style:

<Style x:Key="MyMenuItemStyle" TargetType="{x:Type local:MyMenuItem}">
    <Setter Property="OverridesDefaultStyle" Value="True"/>
    <Style.Triggers>
        <Trigger Property="Role" Value="TopLevelHeader">
            <Setter Property="Template" Value="{StaticResource {x:Static MenuItem.TopLevelHeaderTemplateKey}}"/>
        </Trigger>
        <Trigger Property="Role" Value="TopLevelItem">
            <Setter Property="Template" Value="{StaticResource {x:Static MenuItem.TopLevelItemTemplateKey}}"/>
        </Trigger>
        <Trigger Property="Role" Value="SubmenuHeader">
            <Setter Property="Template" Value="{StaticResource {x:Static MenuItem.SubmenuHeaderTemplateKey}}"/>
        </Trigger>
        <Trigger Property="Role" Value="SubmenuItem">
            <Setter Property="Template" Value="{StaticResource {x:Static MenuItem.SubmenuItemTemplateKey}}"/>
        </Trigger>
    </Style.Triggers>
</Style>

I hope this works for you; It worked for me when I faced the same problem.
Good luck, good code.

Upvotes: 2

Related Questions