views:

1113

answers:

3

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

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

You can easily apply styles or templates to the ContextMenu or MenuItem elements. But if the MenuItem style belongs to the Menu style it is quite cumbersome and redundant to add it to every MenuItem element.

Is there any way to apply those automatically to child elements? So that you can simply write this:

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

It would be neat if FooMenuStyle could style containing MenuItem elements, but that does not seem to be possible.

Edit: The Menu example is probably misleading since I was unaware of ItemContainerStyle and the intent was for a general solution. Based on the two answers I have come up with two solutions: one general variant and one for ItemContainerStyle and the like:

<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>
+4  A: 
<ContextMenu>
   <ContextMenu.Resources>
      <Style TargetType="{x:Type MenuItem}">
         <!--Setters-->
      </Style>
   </ContextMenu.Resources>
   <MenuItem/>
   <!--Other MenuItems-->
</ContextMenu>

The style will be applied to all MenuItem objects within the ContextMenu.

Josh G
I think he already has a style in his resources and would like to apply it to child items, not re-declare it again.
Denis Troller
Moreover, it can be more clearly expressed by using the ItemContainerStyle.
Kent Boogaart
You could declare a new style derived from a previous style.
Josh G
+4  A: 
<ContextMenu ItemContainerStyle="{StaticResource FooMenuItemStyle}">
    <MenuItem/>
</ContextMenu>

HTH, Kent

Kent Boogaart
I think my menu example was a bit misleading (since I did not know about ItemContainerStyle), and the initial intent was for arbitrary elements. But since I actually have a menu this is the way to go.
gix