Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MenuItem Foreground is setting to child menus - only want it on main menu

Tags:

c#

.net

wpf

I have a WPF menu which I set the foreground colour to a binding (using a converter), say the Foreground of my top level menu goes to Green for example, all the child menus under it go green (which I do not want).

Code sample: I want the Finishing Position top menu to go green or whatever the converter tells it do. However I do not want the sub MenuItemDeleteSelection to go to that same colour I want it just to be black or the default greyed out when it's command binding is Can Execute= false).

<Menu>
    <MenuItem Header="{Binding FinishingPosition,Converter={StaticResource FinishingPositionToDisplayTextConverter1}}"  Height="17" Width="12" Padding="0" Name="SelectionStatusHeader" Foreground="{Binding FinishingPosition,Converter={StaticResource FinishingPositionToColourConverter1}}" Background="White" HorizontalContentAlignment="Center">
        <MenuItem Name="MenuItemDeleteSelection" Header="Delete Selection"
                    Command="{Binding Path=DataContext.DeleteSelectionCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" 
                    CommandParameter="{Binding}" />
like image 552
DermFrench Avatar asked Sep 18 '25 03:09

DermFrench


1 Answers

Simply have default style for MenuItem in your Menu resources so that it gets applied automatically to all your menu items.

Set default value to be SystemColors.MenuTextBrushKey which will get applied to all menu items except for the one which overrides it.

<Menu>
   <Menu.Resources>
       <Style TargetType="MenuItem">
           <Setter Property="Foreground"
              Value="{StaticResource {x:Static SystemColors.MenuTextBrushKey}}"/>
       </Style>
    </Menu.Resources>
    <MenuItem Foreground="Green"/>
    <MenuItem/>
    <MenuItem/>
</Menu>
like image 77
Rohit Vats Avatar answered Sep 19 '25 18:09

Rohit Vats