pkr
pkr

Reputation: 1761

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.

Upvotes: 9

Views: 3134

Answers (3)

K Mehta
K Mehta

Reputation: 10553

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

Upvotes: 6

brunnerh
brunnerh

Reputation: 185225

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.

Upvotes: 2

novacara
novacara

Reputation: 2257

TargetType will automatically set the Style on all objects of that type. If you want a specific TextBlock to opt out of the style you can do it like this:

<TextBlock Style="{x:Null}"></TextBlock>

Upvotes: 2

Related Questions