Search code examples
xamlsilverlight

ContentControl (CheckBox) does not inherit Foreground


It looks like the CheckBox control does not inherit its Foreground property:

<UserControl Foreground="Orange">
    <StackPanel>
        <!-- this shows as black - no inheritance -->
        <CheckBox Content="foo" />

        <!-- this shows as turquoise -->
        <CheckBox Foreground="Turquoise" Content="bar" />

        <!-- but this shows as orange - inheritance works here -->
        <TextBlock Text="baz" />
    </StackPanel>
</UserControl>

Screenshot -- "foo" is black, "bar" is turquoise, "baz" is orange

What's the reason for this, and what is the best workaround?

Edit @helb suggested the reason is the default style, which sets the Foreground to black. I don't think this explains it, though: if you override that style and remove the line - <Setter Property="Foreground" Value="#FF000000"/> - the behavior stays the same.


Solution

  • The best I could find is this, which may be an explanation:

    Property value inheritance behavior is not globally enabled for all dependency properties, because the calculation time for inheritance does have some performance impact. Property value inheritance is typically only enabled for properties where a particular scenario suggests that property value inheritance is appropriate.

    So maybe they decided not to apply Foreground inheritance to ContentControls, for performance reasons. Would be nice to be able to confirm this, though. (This answer claims to have used reflector to uncover an opaque hex value, in the internal DP registration, that may have something to do with it.)

    This is one possible workaround (seems adequate, I guess):

    <Style TargetType="CheckBox">
        <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=Foreground}" />
    </Style>
    

    Edit

    More evidence for the "ContentControl doesn't inherit Foreground" theory: Button does not inherit; ComboBox does inherit.