Search code examples
c#wpfxamlwpfdatagriddatagridtemplatecolumn

DataGridTemplateColumn Styling for Disabled Controls WPF


I have a DataGrid control in my WPF application, and I have a checkbox column as one of the columns. I am using a DataGridTemplate to build the data grid. My goal is to change the background color of any checkbox data grid cell where the checkbox is disabled. My checkbox column looks like this:

<!-- style for the checkbox column cells -->
<Style x:Key="DefaultCheckboxCellStyle" TargetType="DataGridCell">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="True">
            <Setter Property="Background" Value="HotPink" />
        </Trigger>
    </Style.Triggers>
</Style>

...
<DataGridTemplateColumn Header="MyCheckBoxColumn" CellStyle="{StaticResource DefaultCheckboxCellStyle}">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Name="chk" IsChecked="{Binding MyChkChecked, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding Path=MyChkEnabled}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
...

Nothing I am doing seems to change the cell background for disabled checkboxes. I am displaying disabled checkboxes, but all of the cells themselves are still enabled. Is there a way to bind the enabled value from the inner checkbox control to the cell? If so, I could use that in my trigger.

Many thanks!


Solution

  • Disabling the checkboxes, as you've, found, won't disable the cells. There are a couple of ways to go about this.

    One is to have the Style trigger bind to the same viewmodel property that disables the checkbox. This belongs in DefaultCheckboxCellStyle, replacing the one trigger you have.

    <Style.Triggers>
        <DataTriger Binding="{Binding MyChkEnabled}" Value="True">
            <Setter Property="Background" Value="HotPink" />
        </DataTriger>
    </Style.Triggers>
    

    Or you could try this in DefaultCheckboxCellStyle: Keep the trigger you have, and disable the actual cell. You could then omit the other XAML that disables the checkbox itself, as it's a child of the cell anyway.

    <Setter Property="IsEnabled" Value="{Binding MyChkEnabled}" />
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="True">
            <Setter Property="Background" Value="HotPink" />
        </Trigger>
    </Style.Triggers>
    

    UpdateSourceTrigger=PropertyChanged is a no-op there, by the way.