1

嗨,这是一个让我疯狂几天的问题。

简单地说,每当我在从 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 库,我想知道这是否会导致问题。

有没有人有任何其他想法?甚至想去哪里调查??

4

2 回答 2

2

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,而不是在其中定义颜色。

于 2013-08-18T09:47:28.233 回答
1

我建议保持您的 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>
于 2013-08-18T09:54:42.140 回答