[英]Custom CheckBox in WPF DataGrid does not update binding
我有以下(简化)风格:
<Style x:Key="MyStyle" TargetType="{x:Type CheckBox}">
<Setter Property="Background" Value="Blue" />
</Style>
如果我在DataGridCheckBoxColumn中将它用作ElementStyle AND EditingElementStyle:
<DataGridCheckBoxColumn Binding="{Binding IsEnabled}"
ElementStyle="{StaticResource MyStyle}"
EditingElementStyle="{StaticResource MyStyle}" />
然后,当我选中/取消选中行的复选框时,我的绑定IsEnabled
不会切换。 如果我删除ElementStyle,EditingElementStyle或两者,那么绑定更新没有问题。 为什么是这样?!
此外,我尝试使用以下代码解决此问题:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsEnabled}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
但问题仍然存在。
对不起,我觉得我在Stack Overflow上找到了一个更好的解决方案,可以帮助人们在这个页面上搜索解决方案。
https://stackoverflow.com/a/7270548/3082531
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
我尝试了这个,它对我来说非常有效,比公认的解决方案更简单,也无需额外点击复选框。
首先你的断言,如果你删除ElementStyle
或EditingElementStyle
解决问题是不正确的,那么什么EditingElementStyle
你就是ElementStyle
。
问题是,为了进行编辑,数据网格必须切换到编辑模板,通常在鼠标单击时进行,但是,由于CheckBox
处理鼠标单击事件,数据网格永远不会得到它,永远不会进入编辑模式,防止您的更改到达您的数据对象(它保留在数据视图中但不会传递给源数据)。
现在您可能会问,默认行为怎么样? 好吧,如果你查看ElementStyle
属性的默认值,你会发现它将IsHitTestVisible
和Focusable
都设置为false。 这可以防止CheckBox
从处理鼠标点击(或键盘事件)改变其状态,并允许数据网格接收他们,这样,它的变化,进入编辑模式,并切换到EditingElementStyle
不影响聚焦能力和命中可测试性。
查看此博客条目以获取有关如何正确执行此操作的示例。 当WPF DataGrid只读CheckBox不是只读时?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.