【问题标题】:WPF Button ControlTemplate won't override Inherited ForegroundWPF 按钮 ControlTemplate 不会覆盖 Inherited Foreground
【发布时间】:2016-10-28 21:40:46
【问题描述】:

Button 的我的全局 (App.xaml) ControlTemplate 不想从默认的黑色覆盖 Foreground 属性。这似乎是一个相对常见的问题,但我尝试了各种解决方案,包括将BasedOn 设置为nulldescribed in this question

我的代码如下,你可以看到我已经尝试在GridContentPresenter 上明确声明前景色。然而颜色保持黑色。 Snoop 告诉我它是默认继承的,但似乎没有说明从哪里继承,并将父 ContentPresenter 显示为将 TextElement.Foreground 设置为正确的颜色。

我应该在这段代码中设置什么吗?我错过了一个元素或属性吗?

<Style TargetType="Button">
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid x:Name="grid" TextBlock.Foreground="#FFD3D3D2">
                    <Border x:Name="border" Background="Transparent" BorderBrush="#FF5C7999" BorderThickness="2" CornerRadius="{Binding RelativeSource={RelativeSource TemplatedParent},Path=ActualHeight,Converter={StaticResource HalfConverter}}" Padding="10">
                        <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0" TextBlock.Foreground="#FFD3D3D2">
                        </ContentPresenter>
                    </Border>
                </Grid>
...

【问题讨论】:

  • 我无法根据您那里的内容重现该问题。按钮出现在什么上下文中?你用什么Content
  • 实际上,我可以重现它:&lt;Button Content="Foo" /&gt; 给我一个灰色的“Foo”。 &lt;Button&gt;&lt;Label&gt;Foo&lt;/Label&gt;&lt;/Button&gt; 给我一个黑色的“Foo”。
  • 我可以在ControlTemplate.Resources 中为Label 添加一个隐含的Style,这将应用于Label 内容。
  • @EdPlunkett 我只看到了您的第一个答案并开始检查内容。请参阅我发布的答案 - 做到了。但是,如果您愿意,我很乐意接受您解释上述内容的答案。
  • 是的,这就是我提出这个问题的地方。我们可能同时对其进行了测试。

标签: c# wpf xaml wpf-controls


【解决方案1】:

原来使用这种样式的按钮将其内容设置为文本以外的内容,或者在内部显式添加了无样式的TextBlock,这覆盖了原始代码中Foreground 属性设置的任何内容。

确保文本被设置为按钮内容,或者确保其包装的样式正确,从而解决了问题。

看来橡皮鸭调试毕竟是有效的。

【讨论】:

    【解决方案2】:

    对此进行测试,如果Button.Content 是字符串,您的Style 会按预期工作,但如果是控件则不会:

    <StackPanel>
        <Button Content="Gray Text As Specified in the ControlTemplate" />
        <Button><Label>Default Black Text</Label></Button>
    </StackPanel>
    

    我可以向ControlTemplate.Resources 添加一个隐式Label 样式,它会覆盖LabelForeground,但是尝试为每个可能的控件设置本地隐式样式是很荒谬的。

    但是,如果您只为 Content 坚持使用纯字符串,它会起作用。现在我要花一些时间研究the inheritance rules for attached properties,因为我认为我有 51% 的半自信认为这不是我通常想要的行为。

    【讨论】:

    • 谢谢埃德。不仅因为“51% 的半自信”而受到支持。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多