覆盖ControlTemplate中ContentPresenter上的默认TextBlock样式

时间:2016-02-26 21:29:21

标签: wpf xaml

我已经找到了一堆针对同一问题的回复,但没有一个真正回答我能说的问题......我试图为我的应用程序设置默认GroupBox样式的标题的前景与其他内容不同的颜色。请考虑以下事项:

<Style TargetType="{x:Type GroupBox}">
    <Setter Property="FontSize" Value="18"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type GroupBox}">
                <ContentPresenter TextElement.Foreground="Green" Content="{TemplateBinding Header}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

现在,如果我将GroupBox上的标题设置为这样的字符串,则字体正确为绿色:

<Grid>
    <GroupBox Header="Header Text"/>
</Grid>

但是,如果我更改它以使标题是控件,则不会应用样式中的字体颜色:

<Grid>
    <GroupBox>
        <GroupBox.Header>
            <TextBlock Text="Header Text"/>
        </GroupBox.Header>
    </GroupBox>
</Grid>

据我所知,这是因为ContentPresenter在第一个例子中只有一个字符串,因此它创建了TextBlock本身,因此它是可视树中的父元素,而在第二个例子中是内容首先创建,然后插入ContentPresenter本来就可以的地方。

所以我知道为什么会发生这种情况......但我还没能找到一个好的解决方法。在其他示例中,我发现人们通常最终明确地模仿内容,但这只是我的应用程序的默认样式,所以我没有内容明确设置任何内容。

1 个答案:

答案 0 :(得分:0)

如果此GroupBox是一次或两次的事情,那么我建议您只是简单地向GroupBox提出x:Name="Whatever",然后绑定所有TextBlock GroupBox您希望它继承到<TextBlock FontSize="{Binding Elementname=Whatever, Path=FontSize}"/> 的1}}属性。 例如:

<TextBlock FontSize="{Binding RelativeSource={RelativeSource, Mode=FindAncestor, AncestorType={x:Type GroupBox}, Path=FontSize}"/>

或者,如果你想避免名字,你可以说......

Unit(String name, double[] initialPosition, int weight, int strength, int agility, int toughness, 
        int currentHealth, int currentStamina) {

理论上,这将允许您将所有内容转储到您可以命名的TextBlock样式&#34; GroupBoxHeaderTextBlockStyle&#34;或者在未来的场景中使用的东西。