Eric Bergman-Terrell's Blog

.NET Programming Tip: How to Commit CheckBox Changes to a WPF DataGrid Immediately
June 12, 2010

By default, A DataGrid cell-level edit is committed when you move to another cell in the same row or press ENTER while the cell is in edit mode. All edits in a row are committed when you move to another row or press ENTER while the row is in edit mode.

These defaults are totally inappropriate for this DataGrid. The user will expect changes to be committed the moment a checkbox's check is toggled. Here's how to ensure that changes take effect immediately:

Add the following AutoCommitCheckBoxColumn class to your application. Note, this class is based upon Samuel Moura's article, with one minor change: Calls to CommitCellEdit were replaced with calls to CheckBox.BindingGroup.CommitEdit:

public class AutoCommitCheckBoxColumn : DataGridCheckBoxColumn
  private void checkBox_Unchecked(object sender, RoutedEventArgs e)
    CheckBox checkBox = (CheckBox)sender;

  private void checkBox_Checked(object sender, RoutedEventArgs e)
    CheckBox checkBox = (CheckBox)sender;

  protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    var checkBox = (CheckBox)base.GenerateEditingElement(cell, dataItem);

    checkBox.Checked += checkBox_Checked;
    checkBox.Unchecked += checkBox_Unchecked;

    return checkBox;

Use AutoCommitCheckBoxColumns instead of DataGridCheckBoxColumns in your DataGrid's XAML markup:

<DataGrid ItemsSource="{Binding Path=Default.FoldersToSearch}" AutoGenerateColumns="False" CanUserAddRows="False" Name="FoldersToSearchGrid" CanUserResizeRows="False" HeadersVisibility="Column">
    <filesearch:AutoCommitCheckBoxColumn Binding="{Binding Path=IsChecked}" Header="Search" SortMemberPath="IsChecked"></filesearch:AutoCommitCheckBoxColumn>
    <DataGridTextColumn Binding="{Binding Path=PathToDisplay}" Header="Path" SortMemberPath="Path" Width="*" IsReadOnly="True"></DataGridTextColumn>

Then, the object data-bound to the checkbox will be updated the moment the user toggles the checkbox's check state.

Keywords: .NET, WPF, DataGrid, CheckBox, Commit, CommitEdit, Data Binding, .NET 4.0, DataGridCheckBoxColumn

Reader Comments

Comment on this Blog Post

Recent Posts

EBTCalc Users: A Desktop Version is Now Available!October 25, 2019
Python Script to Audit MediaMonkey TranscodingAugust 15, 2019
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016