WPF’s DataGridCheckBoxColumn ElementStyle uses a wrong default value


checkbox synopsisToday I found out a strange behavior in the DataGridCheckBoxColumn: it was not using the default template I set in the resources for the CheckBoxes and uses the default WPF’s one instead. This happens always when you set the AutoGeneratedColumns option to true and a work-around exists otherwise.

My fellow geek Jacob Reimers found out that it was a bug in the DataGridCheckBoxColumn’s implementation. Instead of seeking for a Style in the resources, the DataGridCheckBoxColumn creates a new one from scratch and assign it to the CheckBox if you don’t set the ElementStyle property. When the columns are auto-generated, the ElementStyle can’t be set and you have no choice than to have this default style. When you don’t auto-generate the columns, you can set your own custom style and override the default one (happy us !).

A work-around exists(ourah !)

Jacob told me: “why don’t you register to the DataGrid’s AutoGeneratingColumn event and set the ElementStyle there ?“. That’s actually a great idea and it works like a charm. Here is the snippet which performs it:

void grid_AutoGeneratingColumn(object sender,
DataGridAutoGeneratingColumnEventArgs e)
if(e.Column is DataGridCheckBoxColumn)
var checkBoxColumn = e.Column as DataGridCheckBoxColumn;
var resource = Application.Current.FindResource(typeof(CheckBox));
checkBoxColumn.ElementStyle = resource as Style;

As I was porting the Jetpack Theme to WPF I thought it was a little embarrasing to force the users to handle an event just to fix this – little – bug.

So I came up with this enhanced solution in two parts:

  1. an attached property which do exactly the same job than before,
  2. a default style for the DataGrid which set it by default on the DataGrid.

As you are now experts with attached properties, I let you discover the code directly on Codeplex.

On the other hand, here is the default Style setter I use for the DataGrid:
[xml]<Style TargetType="{x:Type DataGrid}">
<Setter Property="helpers:DataGridCheckBoxColumnFixer.Fix" Value="True" />

If you can reproduce this bug, share it on Connect too ! The WPF team have done a great job with this control and this is just a little tiny bug and I hope this will be corrected in the vNext…



4 Responses

  1. Daniel

    05/02/2013 16 h 31 min

    This is how I did it:
    <Controls:DataGridCheckBoxColumn Header="Homme" Binding="{Binding Homme}">
    <Style TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}"/>

  2. Viktor La Croix

    25/03/2013 14 h 34 min

    Great solution, one of the best I have seen actually, but it has one little problem… DataGridCheckBoxColumn now ignores the fact that DataGrid is ReadOnly.

Comments are closed.