WPF Setting the default style on a TextBlock overrides the style for a Label
Asked Answered
T

2

9

Setting the default style on a TextBlock causes the style in the Label and other controls to be set as well. This only happens if you put the styles in the Application resources, when I place the style in the Window resources everything is fine.

I have also found that the VS 2008 Designer and XamlPadX display the Label as you would expect but the problem only occurs if you execute the application in real life.

<Application x:Class="WpfApplication.App"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   StartupUri="Window1.xaml">
   <Application.Resources>
       <ResourceDictionary>
           <Style TargetType="TextBlock">
               <Setter Property="FontSize" Value="8"/>
           </Style>

           <Style x:Key="Title" TargetType="Label">
               <Setter Property="FontSize" Value="32"/>
           </Style>
       </ResourceDictionary>
   </Application.Resources>
</Application>

<Window x:Class="WpfApplication.Window1"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Height="300"
       Title="Window1"
       Width="300">
   <StackPanel>

       <TextBlock Text="TextBlock No Style" Style="{x:Null}"/>
       <Label Content="Label No Style" Style="{x:Null}"/>

       <TextBlock Text="Default TextBlock"/>
       <Label Content="Default Label" Style="{StaticResource Title}"/>

   </StackPanel>
</Window>

The code above displays:

TextBlock No Style - Default font size (As you would expect)
Label No Style - Size 5 font size (How did this happen?)
Default TextBlock - Size 5 font size (As expected by my style)
Default Label - Size 5 font size (How did this happen?)
Tributary answered 5/2, 2010 at 15:43 Comment(0)
W
12

Yes, that's to be expected; look at the default template for Label, it's just an indented TextBlock. Styles are inherited, so the Label will set the FontSize to 32, but then the TextBlock's style will override that. If you just had , it'd be 5pt as well.

Edit: So the way I'd solve this, is to create a dummy subclass (i.e. a class which changes nothing) of TextBlock called NormalText, then style that; this way you won't accidentally pick up other TextBlocks.

Weary answered 5/2, 2010 at 15:51 Comment(0)
T
0

Also, you can try to change the label's content like:

  <Label>
             <Label.Content> 
                 <TextBlock 
                  Text="{Binding Content}"    
                  FontSize="30"></TextBlock> 
             </Label.Content>
   </Label> 
Transcendentalistic answered 24/6, 2022 at 7:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.