Tuesday, June 22, 2010

How to center a check box column in the WPF DataGrid

A common problem with the DataGridCheckBoxColumn of the WPF DataGrid is that the CheckBox is not centered in the cell which is especially ugly in rows that are higher than the CheckBox itself.
Due to the nature of how a column in the DataGrid is generated it isn't very easy to use a simple style or ones own template column.

But there is a much shorter and better way, we can simply extend the DataGridCheckBoxColumn to provide our own, centered, CheckBox.

public class CenteredCheckBoxColumn 
           : DataGridCheckBoxColumn 
{
  protected override FrameworkElement 
    GenerateEditingElement(
      DataGridCell cell, object dataItem) 
  {
    var checkBox = 
      base.GenerateEditingElement(cell, dataItem);
    checkBox.HorizontalAlignment = 
      HorizontalAlignment.Center;
    checkBox.VerticalAlignment = 
      VerticalAlignment.Center;
    return checkBox;
  }

  protected override FrameworkElement GenerateElement(
      DataGridCell cell, object dataItem) 
  {
    var checkBox = 
      base.GenerateElement(cell, dataItem);
    checkBox.HorizontalAlignment = 
      HorizontalAlignment.Center;
    checkBox.VerticalAlignment = 
      VerticalAlignment.Center;
    return checkBox;
  }
}

We can now use our CenteredCheckBoxColumn in the same way we use the standard columns.

Submit this story to DotNetKicks

1 comment:

fleischa said...

Very nice approach so far. Couldn't you also publish the used alignments as properties, so we can set them in XAML (probably not bind them, but anyway)?