I'd like to know whether there's a simple (I believe there's a complex workaround for everything) way to style a group of potentially nested elements while referencing just one style on the parent element level in XAML/WPF.
In HTML/CSS it is possible to do:
<div class="levels"><!--1st level; only reference to the style-->
<div><!--2nd level-->
<div></div><!--3rd level-->
</div>
<div></div><!--2nd level-->
</div>
and then style it by:
.levels {
width: 400px; height: 400px;
background-color:red;}
.levels div {
width: 100px; height: 100px;
background-color:green;}
.levels div div {
width: 50px; height: 50px;
background-color:yellow;}
This makes it possible to reference the style "levels" only once on the parent element and then worry about the referencing no more, so when a new element is added later under the parent element (either in xaml or dynamically in code) you don't need keep in mind to also add "class=levelx" to the new element.
Is the same possible in XAML/WPF? The BasedOn property doesn't seem to be what I want as: a) I'm not looking for a property inheritance, b) unless the new style has a defined x:Key it is applied to all elements of given TargetType and if it does, then once again you need to reference it on the given element (Style="{static resource levelx}"
). <Setter Property="Grid.Grid.Background" Value"Red">
unfortunately doesn't work.
What is then the proper way to style such a group of elements? Referencing a specific style on each nested element seems to me unnecessarily messy.
Here's a concrete example of an element structure, but I consider this to be a general question for many different situations:
<Grid Style="{StaticResource Levels}"><!--1st level-->
<Grid><!--2nd level-->
<Grid></Grid><!--3rd level-->
<Image Source="/Resources/xxx.png"/><!--3rd level-->
</Grid>
<Grid><!--2nd level-->
<Grid></Grid><!--3rd level-->
<Image Source="/Resources/yyy.png" x:Name="yyy"/><!--3rd level-->
</Grid>
<Grid><!--2nd level-->
<Image Source="/Resources/zzz.png"/><!--3rd level-->
</Grid>
</Grid>
This is probably a duplicate, but I couldn't find an answer.