Problem with using CheckBox column in Add Row

Jun 2, 2009 at 2:26 PM

If I include a DataGridCheckBoxColumn and bind it to a Boolean property that defaults to true, then the CheckBox does not work correctly in the Add Row.

The basic flow of actions/events is:

  1. Click on the CheckBox in the add row to give the cell focus
  2. Click on the CheckBox (which is currently unchecked) in the add row to "check" the box
  3. A new row is added
  4. The CheckBox is initialized based on the Boolean property, which is true by default (so the CheckBox is checked).
  5. The DataGrid now passes the click event from #2 to the DataGridCheckBoxColumn, which toggles the CheckBox.
  6. The CheckBox is now unchecked, eventhough it should technically be checked.

Is there something that can be done to prevent this?

Coordinator
Jun 2, 2009 at 8:45 PM

So technically what you're seeing is by-design, but I agree that it could be confusing to the user.

The problem is that the new item is created & bound to the data model before the click is handled.  So it was going checked & then the click was unchecking it.

The reason the new row was unchecked was because it wasn't bound to a data object so it defaulted to un-checked.

It would be less confusing if the new row was checked by default so when the user clicks it & it goes unchecked, it would be expected (since it was checked prior to the click).

Here is how you can do that:

1) make a checkbox derived class that changes the default of IsChecked to true:

<font size="2">

 

</font>

public class CheckBoxDefaultChecked : CheckBox
{<font size="2">

 

</font>

static CheckBoxDefaultChecked()
{
    IsCheckedProperty.OverrideMetadata(
typeof(CheckBoxDefaultChecked), new FrameworkPropertyMetadata(true));
}

}

2) either make a new column type to use it or use a template column:
<font size="2" color="#a31515"><font size="2" color="#a31515">

 

</font></font><font size="2" color="#a31515">

 

</font>

<DataGridTemplateColumn SortMemberPath="IsChecked2" ClipboardContentBinding="{Binding IsChecked2}">
 <DataGridTemplateColumn.CellTemplate>
  <DataTemplate>
   
<src:CheckBoxDefaultChecked IsChecked="{Binding IsChecked2}"/>
  </DataTemplate>
 
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>