ContentControl(CheckBox)不继承Foreground

时间:2015-02-02 16:21:31

标签: xaml silverlight

看起来CheckBox控件不会继承其Foreground属性:

<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

这是什么原因,什么是最好的解决方法?

编辑 @helb建议原因是default style, which sets the Foreground to black。我不认为这解释了它:如果你覆盖那个样式并删除行 - <Setter Property="Foreground" Value="#FF000000"/> - 行为保持不变。

1 个答案:

答案 0 :(得分:0)

我能找到的最好的是this,这可能是一个解释:

  

对于所有依赖项属性,不会全局启用属性值继承行为,因为继承的计算时间确实会对性能产生一些影响。通常仅对特定方案表明属性值继承合适的属性启用属性值继承。

因此,出于性能原因,他们可能决定不将Foreground继承应用于ContentControls。不过,能够证实这一点会很高兴。 (This answer声称在内部DP注册中使用反射器来揭示不透明的十六进制值,这可能与它有关。)

这是一种可能的解决方法(似乎足够了,我猜):

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

修改

更多的证据表明&#34; ContentControl不会继承Foreground&#34;理论:按钮继承; ComboBox 继承。