【问题标题】:How to inherit custom Textblock style in wpf datagrid?如何在 wpf 数据网格中继承自定义文本块样式?
【发布时间】:2015-03-18 16:58:42
【问题描述】:

我在 WPF Datagrid 的 DataGridTemplateColumn 中有 TextBlock。当我选中“IsEnable”false 以继承 DatagridTemplateColumn 内的文本块样式时。这是我正在使用的 XAML 代码:

    <Style TargetType="{x:Type DataGrid}" >
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGrid }">
                    <ControlTemplate.Resources >
                        <Style TargetType="{x:Type TextBlock }">
                            <Style.Triggers>
                                <Trigger Property="IsEnabled" Value="False">
                                    <Setter Property="Foreground" Value="{StaticResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>

                    </ControlTemplate.Resources>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

这不起作用,后来我尝试了:

         <Style  TargetType="TextBlock" >
        <Style.Triggers>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Foreground" Value="{StaticResource {x:Static SystemColors.GrayTextBrushKey}}" />                    
            </Trigger>
        </Style.Triggers>
    </Style>

关于如何检查Datagrid中的Texblock是否“IsEnabled”并继承样式有什么想法吗?

【问题讨论】:

  • tbh 我无法理解您在寻找什么,请尝试解释您的要求
  • 当 isEnabled = false 时你想改变你的文本块的颜色吗?

标签: wpf xaml wpfdatagrid wpf-style


【解决方案1】:

WPF 不会在模板内应用隐式样式,除非 TargetType 派生自 Control。由于 TextBlock 不是从 Control 派生的,因此不会应用其样式。因此,您要么必须手动将样式应用于每个非控件,要么在模板中定义隐式样式。 将 datagrid 资源中的样式定义为

       <DataGrid.Resources>
             <Style TargetType="{x:Type TextBlock}">
               <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                       <Setter Property="Foreground" Value="Red"/>
                     </Trigger>
                </Style.Triggers>
              </Style>
        </DataGrid.Resources>        

【讨论】:

    【解决方案2】:

    我假设您正在尝试根据 TextBlock 的 IsEnabled 状态切换前景色。

    你在哪里设置 IsEnabled = true 前景色?您还没有给出要设置样式的实际 TextBlock 的代码。

    试试这个:

    <Style TargetType="{x:Type TextBlock}">
       <Style.Triggers>
         <Trigger Property="IsEnabled" Value="True">
           <Setter Property="Foreground" Value="Red" />
         </Trigger>
         <Trigger Property="IsEnabled" Value="False">
           <Setter Property="Foreground" Value="Green" />
         </Trigger>
       </Style.Triggers>
    </Style>
    

    如果这不起作用,则意味着无论您的 Textblock 是在哪里定义的,您都在执行此操作 -

    <TextBlock .... Foreground="SomeColor" />
    

    并且需要直接去掉TextBlock上的Foreground设置,这样就可以通过样式来设置Foreground颜色了。

    【讨论】:

      猜你喜欢
      • 2013-07-17
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2011-11-08
      • 2010-10-07
      相关资源
      最近更新 更多