Search code examples
c#wpfdatatemplatemenuitem

C# WPF MenuItem custom template


In Main.xaml I have these two menu items:

  • The first with the header = Disconnect from current
  • The second with the header = Quit
  • ...
  • More menu items with different header texts...

In order to edit some colors of the first item I created a custom template in App.xaml:

<!--Template for Menu Items-->
    <Style x:Key="MenuItemBaseStyle" TargetType="MenuItem">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Background" Value="#0a99f3" />
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type MenuItem}">
                    <Grid Background="{TemplateBinding Background}">
                        <MenuItem Header="DISCONNECT FROM CURRENT" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

And in Main.xaml:

<MenuItem Header="CONNECTION">
    <MenuItem Style="{StaticResource MenuItemBaseStyle}" Header="DISCONNECT FROM CURRENT" />
    <MenuItem Header="QUIT"/>
</MenuItem>

Now I want to do the same for the second menu item. The problem is with the different header. If I delete the header from the template, it won't show any header even if the header text is still present in Main.xaml

How can I use this template for many menu items where the only thing that changes is the header text?


Solution

  • You could just use TemplateBinding on the Header property in the same way you've used it on the Background property:

    <ControlTemplate TargetType="{x:Type MenuItem}">
        <Grid Background="{TemplateBinding Background}">
             <MenuItem Header="{TemplateBinding Header}" />
        </Grid>
    </ControlTemplate>