在样式中定义的TextBlock.Foreground将被忽略

时间:2011-10-12 07:07:20

标签: .net wpf

我在用户控件中使用此样式定义了一个名为Style for TextBlock设置字体大小和前景色以及几个文本块实例。 虽然始终应用样式的FontSize设置,但仅在明确设置文本块的Foreground属性时才应用FontWeight设置。

这是XAML:

请注意,Style和TextBlock实际上不在同一个文件中,而是在同一个程序集中。文本块的大小为22,但前景为黑色。

<Style x:Key="StandardTextBlockStyle" TargetType="TextBlock">
    <Setter Property="FontSize" Value="22" />
    <Setter Property="Foreground" Value="#FF999999"/>
</Style>

<TextBlock Text="Test." 
           Style="{DynamicResource StandardTextBlockStyle}"
           VerticalAlignment="Top"
           Margin="0,5,3,0" 
           Grid.Column="0" 
           Grid.Row="0" />

如果我明确设置了文本块的FontWeight属性(无论是哪个值),都会应用样式的前景设置:

<TextBlock Text="Test." 
           Style="{DynamicResource StandardTextBlockStyle}"
           VerticalAlignment="Top"
           FontWeight="Regular"
           Margin="0,5,3,0" 
           Grid.Column="0" 
           Grid.Row="0" />

我的程序的主要方法基本上是这样的:

[STAThread]
public static void Main()
{
    Application app = new Application();
    Window w = new TestWindow();

    var resource = (ResourceDictionary)Application.LoadComponent(new Uri("/TestProg.UIL;component/SkinBright.xaml", UriKind.RelativeOrAbsolute));
    app.Resources.MergedDictionaries.Add(resource);

    app.Run(w);
}

SkinBright.xaml是包含上述StandardTextBlockStyle的资源字典。

为什么会发生这种情况以及如何避免在所有文本块上设置字体粗细的任何想法?

2 个答案:

答案 0 :(得分:1)

我尝试了你的代码并且它有效(EDIT .NET4.0)

<Grid>
    <Grid.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Grid.Resources>
    <TextBlock Text="Lorem Ipsum"
               Style="{DynamicResource StandardTextBlockStyle}"/>
</Grid>

答案 1 :(得分:0)

尝试:

<Style x:Key="StandardTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">