ContentControl(CheckBox)不继承Foreground
ContentControl (CheckBox) does not inherit Foreground
看起来 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>
这是什么原因,最好的解决方法是什么?
编辑 @helb 提示的原因是default style, which sets the Foreground to black。不过,我认为这并不能解释它:如果您覆盖该样式并删除行 - <Setter Property="Foreground" Value="#FF000000"/>
- 行为保持不变。
我能找到的最好的是this,这可能是一个解释:
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.
因此,出于性能原因,他们可能决定不将 Foreground 继承应用于 ContentControls。不过,能够确认这一点会很好。 (This answer 声称在内部 DP 注册中使用反射器发现了一个不透明的十六进制值,这可能与它有关。)
这是一种可能的解决方法(我想似乎足够了):
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=Foreground}" />
</Style>
编辑
"ContentControl doesn't inherit Foreground" 理论的更多证据:按钮 不 继承; ComboBox 继承。
看起来 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>
这是什么原因,最好的解决方法是什么?
编辑 @helb 提示的原因是default style, which sets the Foreground to black。不过,我认为这并不能解释它:如果您覆盖该样式并删除行 - <Setter Property="Foreground" Value="#FF000000"/>
- 行为保持不变。
我能找到的最好的是this,这可能是一个解释:
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.
因此,出于性能原因,他们可能决定不将 Foreground 继承应用于 ContentControls。不过,能够确认这一点会很好。 (This answer 声称在内部 DP 注册中使用反射器发现了一个不透明的十六进制值,这可能与它有关。)
这是一种可能的解决方法(我想似乎足够了):
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=Foreground}" />
</Style>
编辑
"ContentControl doesn't inherit Foreground" 理论的更多证据:按钮 不 继承; ComboBox 继承。