Reputation: 2210
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.
Upvotes: 9
Views: 9570
Reputation: 32639
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?
Upvotes: 11
Reputation: 354
Sorry for the necro, but I think I found a better solution here on Stack Overflow that might help people ending up on this page searching for a solution.
https://stackoverflow.com/a/7270548/3082531
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
I tried this and it worked perfectly for me, simpler than the accepted solution and also eliminating the need for extra clicks on the checkboxes.
Upvotes: 16