无法覆盖WPF中的标签样式

Jaw*_*har 1 wpf

我在App.xaml中为Label定义了一个样式.

 <Application.Resources>
    <ResourceDictionary>
        <Style TargetType="Label" >
            <Setter Property="Foreground" Value="Blue"/>
        </Style>
        <Style TargetType="TextBlock" >
            <Setter Property="Foreground" Value="Blue"/>
        </Style>
    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

样式适用于我的MainWindow.xaml中的标签Control.但是当我试图在控件上明确设置Foreground时,它不起作用(我不知道).App.xaml中定义的颜色仍在应用(仅适用于Label).

<Grid>
    <Label Content="Label" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    <TextBlock Text="TextBlock" Foreground="Black" VerticalAlignment="Bottom" Height="15.96" Margin="257.537,0,270.003,86" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

相同的逻辑适用于Textblock和所有控件.有什么建议吗?

Bin*_*nil 6

由于为TextBlock设置了样式,您LabelForeground将显示为蓝色

<Style TargetType="TextBlock" >
    <Setter Property="Foreground" Value="Blue"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

您可以在中查看有关此内容的更多详情

Label和TextBlock之间的差异


Lee*_*ell 5

这是一种解释,但不是解决方案;)

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="FontFamily"
            Value="Tahoma" />
    <Setter Property="FontSize"
            Value="{StaticResource StandardFontSize}" />
    <Setter Property="Foreground"
            Value="Black" />
    <Setter Property="VerticalAlignment"
            Value="Center" />
    <Setter Property="HorizontalAlignment"
            Value="Left" />
</Style>    
<Style TargetType="{x:Type Label}">
    <Setter Property="Foreground"
            Value="Black" />
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Text="{Binding}"
                           Foreground="{Binding RelativeSource={RelativeSource AncestorType=Label}, Path=Foreground}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>            
</Style>
Run Code Online (Sandbox Code Playgroud)

如果您像这样定义样式,那么您还可以在网格中设置/覆盖标签前景。因此,这些样式默认标签和文本块为黑色,但如果您愿意,可以更改为蓝色。