【问题标题】:WPF DataGridTemplateColumn IsSelected ForgroundColor not working as expectedWPF DataGridTemplateColumn IsSelected ForgroundColor 未按预期工作
【发布时间】:2011-05-20 21:30:40
【问题描述】:
我有一个DataGrid,其中包含多个DataGridTemplateColumns。
我的问题是当前选定的行会将某些单元格前景变为白色,即使文本变为白色。
包含 TextBlocks 的 DataGridTemplateColumns 行为正确并变为白色,而包含 TextBoxs 的 DataGridTemplateColumns 在选择行时不会改变。
有人知道为什么或如何解决这个问题吗?
我试过这个solution:,但它只能让TextBlocks受到影响,有人知道可能出了什么问题吗?
【问题讨论】:
标签:
wpf
datagrid
datagridtemplatecolumn
【解决方案1】:
我不太确定为什么触发器也不会影响 TextBox ForeGround 但通常当单元格处于编辑模式时选择颜色不应该处于活动状态,因此这可能是 TextBox 拒绝该值的原因,但是我不知道。如果您使用 DataGridTextColumn 并进入编辑模式,您将看到相同的效果,TextBox 不会有 Trigger 的前景,但 TextBlock 会有。要将白色前景应用于 DataGrid 中所有选定的文本框,您可以这样做(请注意,这也会影响处于编辑模式的文本框)
<DataGrid ...>
<DataGrid.Resources>
<Style x:Key="{x:Type DataGridCell}" TargetType="{x:Type DataGridCell}" >
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
<!-- Workaround for the TextBox -->
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}}, Path=IsSelected}" Value="True">
<Setter Property="Foreground" Value="White"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<!-- ... -->
</DataGrid>
【讨论】:
-
显然,根据Moozhe对this answer的评论,您不能默认触发DataGrid的Foreground,因为TextBox.Foreground和Selected Text Foreground是同一个键。