Search code examples
c#wpfdatagrid

How to change background of the template item, on selecting DataGridCell


I need to change the background color of a Textbox that is inside DataGridTemplateColumn cell based on whether or not if the data cell is selected.

Currently what I managed to do is, changing the background color of the template cell, which became useless because of error management.

Thus, I want to change the background of the Textbox, and revert it back on selection changed.

  <DataGrid.Resources>
                <Style TargetType="{x:Type DataGridRow}">
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="DarkBlue"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </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"  Style="{StaticResource TextBoxValidated}"/>
                              
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

Solution

  • You could use a Style with a DataTrigger that binds to the IsSelected property of the parent row:

    <DataGridTemplateColumn IsReadOnly="True" MinWidth="150" Width="*">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=TwoDLineName, Mode=TwoWay,UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True}">
                    <TextBox.Style>
                        <Style TargetType="TextBox" BasedOn="{StaticResource TextBoxValidated}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsSelected,
                                    RelativeSource={RelativeSource AncestorType=DataGridRow}}"
                                             Value="True">
                                    <Setter Property="Background" Value="Red" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBox.Style>
                </TextBox>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>