What is equivalent to the HTML class id in WPF?

I have several StackPanels, I want to have the same width. However, this should not affect all StackPanels, and I do not want subclasses just for that. 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 that TextBlock does not know its style (for example, when HTML is different from the CSS rule that applies to the element)?

I would just like to provide all the relevant StackPanels with the same class identifier, and then apply the style to the class identifier.

+4
source share
3 answers

Unfortunately, this is not possible in WPF. Closest you can come to this - this is what you demonstrated in your example.

However, if you want to apply the style to all the StackPanels in the root container the same , you can specify the style as the resource of the root container, leaving the x:Key attribute. 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

+4
source

Unfortunately not, but you can create an attached property to set the class, and then apply the style implicitly to all text blocks, but use Triggers in this attached property to decide which setters to apply. The disadvantage of this is that it is still not very pleasant, but also that the functionality of the style is limited, since you cannot use triggers in the litter.

+1
source

TargetType automatically sets the style for all objects of this type. If you want a specific TextBlock to abandon the style, you can do it like this:

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

Source: https://habr.com/ru/post/1383744/


All Articles