【问题标题】:Cannot override controls foreground colour in wpf无法覆盖 wpf 中的控件前景色
【发布时间】:2013-08-20 07:13:10
【问题描述】:

大家好,这是一个让我发疯好几天的问题。

简单地说,每当我在从 TextBlock 控件派生的任何东西上声明前景色时,前景色在设计时被识别,但在运行时它总是默认为黑色。

就好像在控件上忽略了前景属性。

因此,例如,通常我希望以下内容呈现带有白色文本的按钮:

<Button x:Name="MyButton" Content="Hello World" Foreground="White" ... />

但是,这会呈现一个按钮,并且前景文本颜色为黑色。它有效地忽略了 Foreground setter 属性。

让它按预期工作的唯一方法是执行以下操作:

<Button x:Name="MyButton" .... >
     <TextBlock Text="Hello World" Foreground="White"/>
</Button>

这种方式有效,并且按钮可以正确呈现白色文本。但我知道我不应该像这样明确定义按钮文本块。

从文本块派生的任何内容都会发生相同的行为。

有人知道为什么会这样吗?

更新: 我已经检查了应用于 TextBox 的样式的解决方案。我在 TextBlock 上定义了自己的样式:

<Style x:Key="TextBlockText" TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="#FF63798F"/>
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="VerticalAlignment" Value="Bottom"/>
    <Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>

如您所见,它定义了前景的值。 但是当我从我的资源字典中删除这种样式时,上述问题仍然存在。

其他信息是我正在使用 MahApps.Metro 库,我想知道这是否是导致问题的原因。

有人有其他想法吗?或者甚至是去哪里调查的想法??

【问题讨论】:

  • 你确定吗?这对我有用&lt;Button Content="Hello World" Foreground="White"/&gt;
  • 您可能有一个将前景设置为黑色的 TextBlock 默认样式,请查看 TargetType="{x:Type TextBlock} 的整个解决方案
  • 同时检查 TargetType="Button" 或 ButtonBase。样式肯定有问题。
  • @RohitVats 我确信这是我想要发生的事情,但不幸的是它没有发生。
  • @makc 我也对此进行了检查,我拥有的唯一文本块样式是我自己专门定义的样式。我删除了这个问题仍然存在。

标签: c# .net wpf


【解决方案1】:

WPF 中的每个控件都有一个与之关联的模板。我认为以某种方式在您的按钮上定义的样式不计算前景属性。

例如,

    <Style x:Key="DialogButtonStyle" TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <Ellipse Fill="{TemplateBinding Background}"
                             Stroke="{TemplateBinding BorderBrush}"/>
                       <TextBlock Foreground="{TemplateBinding Foreground}">
                        <ContentPresenter HorizontalAlignment="Center"
                                          VerticalAlignment="Center"/></TextBlock>
                </Grid>            
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

您能否使用 Style={StaticResource DialogBu​​ttonStyle} 并为按钮定义前景​​。请参阅此处,我们在 TextBlock 的 Foreground 上使用了 TemplateBinding,而不是在其中定义颜色。

【讨论】:

    【解决方案2】:

    我建议保持您的 TextBlock 样式不变,并在您的 Button 或其他控件中,在模板级别添加一个具有 TextBlock 样式的新资源。它将位于该模板的域中,因此不会影响其他文本块,但会覆盖主 TextBlock 的样式。

    例如:

    <ControlTemplate>
      <Grid>
        <Grid.Resources>
              <!-- Put a new/duplicate TextBlock Style here with 
                   the appropriate Foreground color, or TemplateBinding 
                   and it will override it for this Grid's children -->
        </Grid.Resources>
        <TextBlock />
      </Grid>
    </ControlTemplate>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-26
      • 2022-01-23
      • 2014-11-22
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多