2010-05-28 97 views
8

我有以下的(简化)风格:自定义复选框在WPF DataGrid不更新绑定

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

如果我把它作为ElementStyle和EditingElementStyle在我DataGridCheckBoxColumn:

<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> 

然而,问题依然存在。

回答

11

首先,你的断言,如果你删除ElementStyleEditingElementStyle解决了这个问题是不正确的,什么螺丝钉是ElementStyle

问题是,要进行编辑,数据网格必须切换到编辑模板,通常在鼠标单击时执行该模板,但是,由于CheckBox处理鼠标单击事件,数据网格永远不会获取它,并且永远不会进入编辑模式,阻止您的数据对象的更改(它保留在数据视图内,但不会传递到源数据)。

现在你可能会问,默认行为怎么样?那么,如果您查看ElementStyle媒体资源的默认值,则会注意到它将IsHitTestVisibleFocusable都设置为false。这可以防止CheckBox处理改变其状态的鼠标点击(或键盘事件),并允许数据网格接收它们,从而改变它进入编辑模式并切换到不影响可聚焦性并击中的EditingElementStyle可测试性。

退房有关如何做到这一点的权利When is a WPF DataGrid read-only CheckBox not read-only?

10

对不起,死灵为例此博客条目,但我想我找到了一个更好的解决方案在这里对堆栈溢出,这可能有助于人们对这个网页的搜索结束了寻求解决方案。

https://stackoverflow.com/a/7270548/3082531

<DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
     <CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}" /> 
    </DataTemplate> 
</DataGridTemplateColumn.CellTemplate> 

我想这和它完美的工作对我来说,比接受的解决方案更简单,也省去了额外的复选框点击的需要。

+0

同意 - 这是非常简单的。 – ifinlay 2016-01-21 22:42:04