LWChris
LWChris

Reputation: 4201

Can I apply a style to a XAML element based on what parent element it has?

What is the correct way to apply styles on elements with a condition on their parent element's type, i. e. only if they are children of certain other elements?

In my case, I want to apply some exact button width and height, but only if those buttons are direct children of a stackpanel. Additionally, a second style should be applied to images within those buttons (glyphs).

As 90% of all buttons in my application are those on the stackpanels, so far I've applied the style to all buttons and images and overrode it where necessary. But this isn't the best solution, is it?

Preferably, the solution would deal with all the conditions in the style definition, so I won't have to explicitly assign that style to every single one of my stackpanels.

Upvotes: 1

Views: 1047

Answers (1)

<StackPanel>
   <StackPanel.Resources>
      <Style x:Key="Rectangle1" TargetType="Rectangle">
        <Setter Property="Stroke" Value="Black" />
        <Setter Property="Fill" Value="White" />                                            
      </Style>                                      
   </StackPanel.Resources>
   <UniformGrid Columns="10">
      <UniformGrid.Resources>
         <Style TargetType="Rectangle" BasedOn="{StaticResource Rectangle1}">
            <Setter Property="Fill" Value="Red" />                                          
     </Style>                                       
      </UniformGrid.Resources>

    </UniformGrid>
</StackPanel>

Upvotes: -1

Related Questions