Thursday, May 5, 2011

Creating DataGridTemplateColumn from code behind

We can create DataGridTemplateColumn from code behind by defining a DataTemplate in the ResourceDictionary xaml and then use the DataTemplate to create the DataGridTemplateColumn.

In the below sample code, I am creating a data grid column with checkbox.

In the ResourceDictionary xaml, add DataTemplate for the checkbox:


<DataTemplate x:Key="CheckboxTemplate">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
</DataTemplate>

From the code behind create the DataGridTemplateColumn for the checkbox:


DataGridTemplateColumn checkboxColumn = new DataGridTemplateColumn()
{
      CellTemplate = App.Current.Resources["CheckboxTemplate"] as DataTemplate
};

Double click issue with DataGridCheckbox column

DataGridCheckboxColumn in DataGrid seems to have double click issue. One has to click twice to check or uncheck, first click to select the row and the second click for the checkbox. We can use DataGridTemplateColumn instead for the checkbox which does not have double click issue. 

sample code:

<DataGridTemplateColumn Header="Name">
<controlsData:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" IsChecked="{Binding Path=IsSelected,Mode=TwoWay}" />
</DataTemplate>
</controlsData:DataGridTemplateColumn.CellTemplat>
</DataGridTemplateColumn>