I have some StackPanels I wish to have the same Width. However this should not affect all StackPanels and I do not want to subclass just for this. I know that the following is possible:
<Style BasedOn="{StaticResource {x:Type TextBlock}}"
TargetType="TextBlock"
x:Key="TitleText">
<Setter Property="FontSize" Value="26"/>
</Style>
...
<TextBlock Style="{StaticResource TitleText}">
Some Text
</TextBlock>
But is there a way to keep the TextBlock ignorant of its Style (like it is when the HTML is separate from the CSS rule that applies to the element)?
I would just like to give all the relevant StackPanels the same class id, and then apply the style to the class id.
Unfortunately, this is not possible in WPF. The closest you can come to this is what you've demonstrated in your example.
However, if you want to apply a style to all StackPanels in the same root container, you can specify the Style as a resource of the root container, leaving the x:Key
attribute out. As an example:
<Grid x:Name="LayoutRoot">
<Grid x:Name="StackPanelsRoot">
<Grid.Resources>
<Style TargetType="StackPanel">
...
</Style>
</Grid.Resources>
<StackPanel x:Name="SP1" ... />
<StackPanel x:Name="SP2" ... />
...
</Grid>
<StackPanel x:Name="SP3" ... />
...
</Grid>
Here, the Style will be applied to SP1
and SP2
, but not to SP3
Sadly there is not, but you could create an attached property to set a class and then apply a style implicitly to all textblocks but use Triggers
on that attached property to decide which setters to apply. The downside of that is that it is still not very nice of course but also that the functionality of the style is limited, as you cannot use triggers in a substyle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With