2017-03-19 55 views
2

DataGridCheckBoxColumn的默認行爲是用戶必須單擊兩次以更改複選框值。在How to perform Single click checkbox selection in WPF DataGrid主題中有幾個解決方案可行,但存在一個問題 - 您是否有代碼隱藏的視圖模型對象,它實現IEditableObject接口,然後EndEdit方法不會執行。如何使用IEditableObject對象在WPF DataGrid中執行單擊複選框選擇

任何想法如何使單擊工作,並保留IEditableObject功能性?

回答

5

你可以處理GotFocus事件爲DataGrid,明確進入編輯模式,並檢查/取消選中CheckBox

private void dg_GotFocus(object sender, RoutedEventArgs e) 
{ 
    DataGridCell cell = e.OriginalSource as DataGridCell; 
    if (cell != null && cell.Column is DataGridCheckBoxColumn) 
    { 
     dg.BeginEdit(); 
     CheckBox chkBox = cell.Content as CheckBox; 
     if (chkBox != null) 
     { 
      chkBox.IsChecked = !chkBox.IsChecked; 
     } 
    } 
} 

<DataGrid x:Name="dg" AutoGenerateColumns="False" GotFocus="dg_GotFocus"> 
    <DataGrid.Columns> 
     <DataGridCheckBoxColumn Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" /> 
     ...