WPF - Change DataGridTemplateColumn cell background based on CheckBox value

风流意气都作罢 提交于 2019-12-24 13:26:38

问题


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.


回答1:


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}"/>


来源:https://stackoverflow.com/questions/17618077/wpf-change-datagridtemplatecolumn-cell-background-based-on-checkbox-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!