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}"> <Setter Property="ItemContainerStyle" Value="{StaticResource FooMenuItem}"/> <Style.Resources> <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource FooMenuItem}"/> </Style.Resources> </Style> <ContextMenu Style="{StaticResource FooMenu}"> <MenuItem/> </ContextMenu>
nested styles wpf children
gix Mar 20 '09 at 14:03 2009-03-20 14:03
source share