1
votes

I have defined a named Style for TextBlock setting font size and foreground color and several textblock instances using this style within user controls. While the FontSize setting of the style is always applied, the Foreground setting is only applied if the FontWeight property of the text block is explicitly set.

Here's the XAML:

Note that Style and TextBlock are actually not in the same file, but in the same assembly. The text block is rendered in size 22 but with black foreground.

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

If I set the FontWeight property of the text block explicitly (no matter to which value), the foreground setting of the style is applied:

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

The main method of my program basically looks like this:

[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 is the resource dictionary which contains the StandardTextBlockStyle mentioned above.

Any ideas why this happens and how to avoid the need to set the font weight on all text blocks?

2
how to your import your style to your resources? - blindmeis
What version of WPF are you using? - Kent Boogaart
@Kent Boogaart: It's WPF 4.0 (updated title accordingly). - Mathias Koch
@blindmeis: I don't, I'm adding the resource dictionary to the application in code. Since the font size of the style is set properly, not finding the style can't be the issue. - Mathias Koch
@Mathias: can you perhaps expand your question to show exactly how and where you're adding the resource dictionary? - Kent Boogaart

2 Answers

1
votes

i tried your code and it works (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>
0
votes

Try:

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