2010-05-28 99 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