Styling nested elements in WPF

Suppose you have a nested element structure, for example ContextMenu with MenuItems:

<ContextMenu Style="{StaticResource FooMenuStyle}"> <MenuItem Style="{StaticResource FooMenuItemStyle}"/> ... </ContextMenu> 

You can easily apply styles or templates to ContextMenu or MenuItem elements. But if the MenuItem style is related to the menu style, it is rather cumbersome and redundant to add it to every MenuItem element.

Is there a way to apply them automatically to child elements? So you can just write this:

 <ContextMenu Style="{StaticResource FooMenuStyle}"> <MenuItem/> ... </ContextMenu> 

It would be convenient if FooMenuStyle could style MenuItem elements, but this is not possible.

Edit: The example menu is probably misleading since I did not know about ItemContainerStyle and the goal was for a general solution. Based on two answers, I came up with two solutions: one general option and one for ItemContainerStyle, etc.:

 <Style x:Key="FooMenuItem" TargetType="{x:Type MenuItem}"> ... </Style> <Style x:Key="FooMenu" TargetType="{x:Type ContextMenu}"> <!-- Variant for specific style attribute --> <Setter Property="ItemContainerStyle" Value="{StaticResource FooMenuItem}"/> <!-- General variant --> <Style.Resources> <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource FooMenuItem}"/> </Style.Resources> </Style> <ContextMenu Style="{StaticResource FooMenu}"> <MenuItem/> </ContextMenu> 
+49
nested styles wpf children
Mar 20 '09 at 14:03
source share
3 answers
 <ContextMenu> <ContextMenu.Resources> <Style TargetType="{x:Type MenuItem}"> <!--Setters--> </Style> </ContextMenu.Resources> <MenuItem/> <!--Other MenuItems--> </ContextMenu> 

The style will apply to all MenuItem objects in ContextMenu.

+17
Mar 20 '09 at 14:07
source share

To complete the original answer, I think that clearly adding a nested style inside the parent type:

 <Style x:Key="WindowHeader" TargetType="DockPanel" > <Setter Property="Background" Value="AntiqueWhite"></Setter> <Style.Resources> <Style TargetType="Image"> <Setter Property="Margin" Value="6"></Setter> <Setter Property="Width" Value="36"></Setter> <Setter Property="Height" Value="36"></Setter> </Style> <Style TargetType="TextBlock"> <Setter Property="TextWrapping" Value="Wrap"></Setter> </Style> </Style.Resources> </Style> 
+117
Nov 02 '10 at 13:45
source share
 <ContextMenu ItemContainerStyle="{StaticResource FooMenuItemStyle}"> <MenuItem/> </ContextMenu> 
+6
Mar 20 '09 at 14:27
source share



All Articles