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;
    checkBox.BindingGroup.CommitEdit();
  }

  private void checkBox_Checked(object sender, RoutedEventArgs e)
  {
    CheckBox checkBox = (CheckBox)sender;
    checkBox.BindingGroup.CommitEdit();
  }

  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">
  <DataGrid.Columns>
    <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>
  </DataGrid.Columns>
</DataGrid>

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

TitleDate
Node.js + Express: How to Block Requests by User-Agent HeadersJanuary 7, 2026
Vault 3 is Now Available for Windows on ARM Machines!December 13, 2025
Vault 3: How to Include Outline Text in Exported PhotosOctober 26, 2025
.NET Public-Key (Asymmetric) Cryptography DemoJuly 20, 2025
Raspberry Pi 3B+ Photo FrameJune 17, 2025
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023