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
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
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015
Node.js / Express Programming Tip: Detect and Fix Memory LeaksOctober 27, 2015