views:

221

answers:

1

In my Visual Studio 2010 WPF application, I have the following (simplified) style:

<Style x:Key="MyStyle" TargetType="{x:Type CheckBox}">  
    <Setter Property="Background" Value="Blue" />  
</Style>

If I use it as the ElementStyle AND EditingElementStyle in my DataGridCheckBoxColumn:

<DataGridCheckBoxColumn Binding="{Binding IsEnabled}"  
    ElementStyle="{StaticResource MyStyle}"  
    EditingElementStyle="{StaticResource MyStyle}" />

Then my binding, IsEnabled, does not toggle when I check/uncheck a row's checkbox. If I remove either ElementStyle, EditingElementStyle, or both, then the binding updates no problem. Why is this?!

Also, I tried to work around the problem using the following code:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding IsEnabled}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

However, the problem remains.

A: 

First of all your assertion that if you remove either ElementStyle or EditingElementStyle solves the issue is not correct, what screws you over is the ElementStyle.

The thing is, that for editing to take place the data grid must switch to the editing template, which it normally does on a mouse click, however, since the CheckBox handles the mouse click event, the data grid never gets it, and never goes into editing mode, preventing your change from ever reaching your data objects (it stays within the data view but doesn't get passed over to the source data).

Now you may be asking, how come the default behavior is ok? Well if you look into the default value of the ElementStyle property, you'll notice that it is setting both IsHitTestVisible and Focusable to false. This prevents the CheckBox from handling the mouse click (or keyboard event) that changes its state, and allows the data grid to receive them, thus giving it a change to enter editing mode and switch to the EditingElementStyle which doesn't affect focusability and hit testability.

Check out this blog entry for an example on how to do this right When is a WPF DataGrid read-only CheckBox not read-only?

Aviad P.