Note that there are some explanatory texts on larger screens.

plurals
  1. POStyling nested elements in WPF
    primarykey
    data
    text
    <p>Suppose you have a nested element structure, for example a ContextMenu with MenuItems:</p> <pre><code>&lt;ContextMenu Style="{StaticResource FooMenuStyle}"&gt; &lt;MenuItem Style="{StaticResource FooMenuItemStyle}"/&gt; ... &lt;/ContextMenu&gt; </code></pre> <p>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.</p> <p>Is there any way to apply those automatically to child elements? So that you can simply write this:</p> <pre><code>&lt;ContextMenu Style="{StaticResource FooMenuStyle}"&gt; &lt;MenuItem/&gt; ... &lt;/ContextMenu&gt; </code></pre> <p>It would be neat if FooMenuStyle could style containing MenuItem elements, but that does not seem to be possible.</p> <p>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:</p> <pre><code>&lt;Style x:Key="FooMenuItem" TargetType="{x:Type MenuItem}"&gt; ... &lt;/Style&gt; &lt;Style x:Key="FooMenu" TargetType="{x:Type ContextMenu}"&gt; &lt;!-- Variant for specific style attribute --&gt; &lt;Setter Property="ItemContainerStyle" Value="{StaticResource FooMenuItem}"/&gt; &lt;!-- General variant --&gt; &lt;Style.Resources&gt; &lt;Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource FooMenuItem}"/&gt; &lt;/Style.Resources&gt; &lt;/Style&gt; &lt;ContextMenu Style="{StaticResource FooMenu}"&gt; &lt;MenuItem/&gt; &lt;/ContextMenu&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload