user1017477
user1017477

Reputation: 161

WPF - Change DataGridTemplateColumn cell background based on CheckBox value

I need to change the background color of a DataGridTemplateColumn cell based on whether or not the CheckBox within the DataGridTemplateColumn is checked. Seems that this should be possible within xaml, how can I go about this?

Column:

<DataGridTemplateColumn Header="FSC-P" Width="SizeToHeader">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding FSCP}" 
                      VerticalAlignment="Center" 
                      HorizontalAlignment="Center" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

I have seen this post however, this is not working for a TemplateColumn. Any help would be appreciated.

Upvotes: 1

Views: 7232

Answers (1)

Richard E
Richard E

Reputation: 4919

The following Style will change the Background color of the Cell if the CheckBox is checked:

    <Style x:Key="CheckBoxCellStyle" TargetType="DataGridCell">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <CheckBox x:Name="cb"
                              IsChecked="{Binding FSCP, UpdateSourceTrigger=PropertyChanged}" 
                              VerticalAlignment="Center" 
                              HorizontalAlignment="Center" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <DataTrigger Binding="{Binding FSCP, UpdateSourceTrigger=PropertyChanged}" Value="True">
                <Setter Property="Background" Value="Blue"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

<DataGridTemplateColumn Header="FSC-P" Width="SizeToHeader" CellStyle="{StaticResource CheckBoxCellStyle}"/>

Upvotes: 3

Related Questions