【问题标题】:How do I set the foreground color of any child element in a Grid from the Grid's style?如何根据 Grid 的样式设置 Grid 中任何子元素的前景色?
【发布时间】:2012-08-25 05:28:30
【问题描述】:

如何在网格样式中设置Grid 中所有子元素的Foreground 颜色?我知道我以前做过,但我不记得在哪里或如何做。

<Style x:Key="MyGridStyle" TargetType="{x:Type Grid}">
    // I want to set the font color here
</Style>

<Grid Style="{StaticResource MyGridStyle}">
    ...
</Grid>

我知道我可以使用

<Grid.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Red" />
    </Style>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Grid.Resources>

但是我想在Style 中设置这个值,而不是在Grid

【问题讨论】:

    标签: wpf xaml styles


    【解决方案1】:

    想通了,我只需要在&lt;Style.Resources&gt;中设置默认样式

    <Style x:Key="MyGridStyle" TargetType="{x:Type Grid}">
        <Style.Resources>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Foreground" Value="Red" />
            </Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Foreground" Value="Red" />
            </Style>
        </Style.Resources>
    </Style>
    

    【讨论】:

      【解决方案2】:

      怎么样:

      <Style x:Key="MyGridStyle" TargetType="{x:Type Grid}">
          <Setter Property="TextElement.Foreground" Value="Red"/>
      </Style>
      

      【讨论】:

      • 有效,但仅适用于 TextBlocks。使用&lt;Style.Resources&gt; 可以让我设置TextBoxes 和其他控件的样式。如果您的面板仅包含 TextBlock 元素,则 +1 无论如何都是一种更简洁的方式
      • 大声笑,是的,我正在使用TextBlock 元素进行测试,但我的实际网格也包含TextBoxes。在您发布答案之前,我没想到要做出区分:)
      • 当我尝试为 Border 控件内的所有孩子应用 Foreground 时,它解决了我的问题。
      猜你喜欢
      • 2020-07-28
      • 2018-11-28
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2018-01-06
      相关资源
      最近更新 更多