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:Keyattribute out. As an example:Here, the Style will be applied to
SP1andSP2, but not toSP3