1

I have two styles set in my UserControl.Resources

    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="white" />
    </Style>
    <Style TargetType="{x:Type Label}">
        <Setter Property="Foreground" Value="white" />
    </Style>

So that in my DataTemplate (and note that I chopped the rest off) I will have white text applied without having to change the properties on each and every Label and TextBlock element.

<DataTemplate x:Key="FileTransferItemTemplate">
        <StackPanel Orientation="Vertical">
            <StackPanel Orientation="Horizontal">
                <Label Content="Transferring With: " />
                <TextBlock Text="{Binding Path=OtherUserName, Mode=TwoWay}" />
            </StackPanel>
</DataTemplate>

What happens though(and this caused me a long nightmare where I thought I was databinding improperly because I couldn't see any changes), is when the data is bound the foreground color defaults to black. My databound text was black on a black background, and I didn't even realize for the longest time.

The only way I can override this is manually setting the Foreground="White" on the TextBlock. The Label works fine for the color, because it's not databound.

Why is this happening, and how can I fix it?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Cowman
  • 678
  • 7
  • 25
  • If you replace the binding by some text, you'll realize that the problem hasn't got anything to do with the binding. – Clemens Jan 05 '13 at 21:55
  • Default style for TextBlock seems to be ignored in a DataTemplate. Found [this question](http://stackoverflow.com/q/13293627/1136211), although it's Silverlight, not WPF. See also [this page](http://www.11011.net/archives/000692.html). – Clemens Jan 05 '13 at 22:10

1 Answers1

3

The problem is not related to binding. It just seems that the lookup of an externally defined default style from inside a DataTemplate only works for elements that are derived from Control. Since TextBlock isn't derived from Control, your default style is not found.

This page cites the following two statements given by Microsoft:

This behavior is 'By Design' and this is why. Templates are viewed as an encapsulation boundary. Elements produced by these templates fall within this boundary. And lookup for a style with a matching TargetType stops at this boundary. Hence the TextBlock in the repro which is produced through a template does not pick up the Style in question. Whereas the TextBlock defined outside the template does. One way to work around this problem is to give an explicit name to the Style and reference the style by this name on the TextBlock within the template.

and

Templates are viewed as an encapsulation boundary when looking up an implicit style for an element which is not a subtype of Control.

Clemens
  • 123,504
  • 12
  • 155
  • 268