You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

选中DataGridCell时如何更改DataGridTemplateColumn内TextBox的背景色

WPF DataGrid选中模板列时修改内部TextBox背景的实现方案

核心实现逻辑是通过绑定父级DataGridCell的选中状态触发TextBox样式变更,不影响原有验证错误管理逻辑。

修改后完整代码

你原有DataGrid.Resources里的行样式可按需保留或删除,模板列部分修改如下:

<DataGrid.Columns>
    <DataGridTemplateColumn IsReadOnly="True" MinWidth="150" Width="*">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=TwoDLineName, Mode=TwoWay,UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
                     HorizontalAlignment="Stretch">
                    <TextBox.Style>
                        <!-- 继承原有验证样式,不破坏错误管理逻辑 -->
                        <Style TargetType="TextBox" BasedOn="{StaticResource TextBoxValidated}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}}}" Value="True">
                                    <Setter Property="Background" Value="DarkBlue"/>
                                    <Setter Property="Foreground" Value="Black"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBox.Style>
                </TextBox>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

说明

  • 选中对应单元格时,TextBox自动切换为触发设置的背景和前景色,选中状态取消后自动恢复原有样式,验证错误时的特殊样式优先级高于该触发,不会被覆盖,完全满足错误管理需求
  • 如果需要整行选中时当前行所有模板列的TextBox都改样式,只需要把触发里的AncestorType={x:Type DataGridCell}改为AncestorType={x:Type DataGridRow}即可
  • 如需全局生效,直接把上述DataTrigger添加到你的TextBoxValidated静态样式中即可,无需每个TextBox重复定义

内容的提问来源于stack exchange,提问作者Sugee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:54:04