Today 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:
[csharp]
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;
}
}
[/csharp]
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:
- an attached property which do exactly the same job than before,
- 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" />
</Style>[/xml]
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…
Regards.
05/02/2013 16 h 31 min
This is how I did it:
<Controls:DataGrid.Columns>
<Controls:DataGridCheckBoxColumn Header="Homme" Binding="{Binding Homme}">
<Controls:DataGridCheckBoxColumn.ElementStyle>
<Style TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}"/>
</Controls:DataGridCheckBoxColumn.ElementStyle>
</Controls:DataGridCheckBoxColumn>
</Controls:DataGrid.Columns>
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.