【问题标题】:WPF Setting the default style on a TextBlock overrides the style for a LabelWPF 在 TextBlock 上设置默认样式会覆盖标签的样式
【发布时间】:2026-02-17 10:30:01
【问题描述】:

在 TextBlock 上设置默认样式会导致 Label 和其他控件中的样式也被设置。仅当您将样式放在应用程序资源中时才会发生这种情况,当我将样式放在窗口资源中时,一切都很好。

我还发现 VS 2008 Designer 和 XamlPadX 会按预期显示标签,但只有在现实生活中执行应用程序时才会出现问题。

<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>

上面的代码显示:

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?)

【问题讨论】:

    标签: wpf styles default font-size textblock


    【解决方案1】:

    是的,这是意料之中的;查看Label的默认模板,它只是一个缩进的TextBlock。样式是继承的,因此 Label 会将 FontSize 设置为 32,但随后 TextBlock 的样式将覆盖该值。如果你只是有,那也是5pt。

    编辑:所以我解决这个问题的方法是创建一个名为 NormalText 的 TextBlock 的虚拟子类(即一个不会改变任何内容的类),然后设置它的样式;这样你就不会意外拾取其他 TextBlocks。

    【讨论】: