选中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
相关产品推荐
相关产品推荐

