Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of HTML class id's in WPF?

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.

like image 255
pkr Avatar asked Nov 29 '11 21:11

pkr


2 Answers

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

like image 119
K Mehta Avatar answered Sep 19 '22 10:09

K Mehta


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.

like image 20
H.B. Avatar answered Sep 19 '22 10:09

H.B.