Tuesday, February 12, 2013

WPF- What’s Going On With My DataGrid Checkbox?

This is a very common mistake and I found myself committing it recently.

Sometimes you will find yourself wanting to create a datagrid column that contains a checkbox. The simplest way of doing this is by defining a DataGridCheckBoxColumn.

<DataGridCheckBoxColumn Binding="{Binding IsSelected}"/>


There are some situations when you might want to use a DataGridTemplateColumn instead because you want to tweak some visuals or add other controls inside the cell.


<DataGridTemplateColumn Width="30">
<
DataGridTemplateColumn.CellTemplate>
<
DataTemplate>
<CheckBox IsChecked="{Binding IsSelected}"/>
</DataTemplate>
</
DataGridTemplateColumn.CellTemplate>
</
DataGridTemplateColumn>


When people do this, they sometimes find that the bindings don’t work properly. If they click on the checkbox, they notice that the property they are binding to (in this case IsSelected) does not update until you click somewhere else in the cell. Some people even miss this and just think the binding does not work at all. I ran across a case where a developer had two datagrid columns side by side, one was the DataGridCheckBoxColumn and the other one was a DataGridTemplateColumn like the ones above. The developer was convinced that something was going on because the binding was working for one and not the other.



If you run into this, don’t worry. The binding is working. It’s just not updating the bound property at the correct time. To fix this, simply make the following tweak to the binding statement. This should now cause the property to change immediately once the checkbox is checked (once the IsChecked property changes).



<DataGridTemplateColumn Width="30">
<
DataGridTemplateColumn.CellTemplate>
<
DataTemplate>
<CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</
DataGridTemplateColumn.CellTemplate>
</
DataGridTemplateColumn>


That’s it. Hope this helps.

Happy Coding!



No comments:

Post a Comment