Search code examples
c#wpfxamldatagridwpftoolkit

WPF Toolkit Datagrid - how do you turn selection off?


I have a datagrid in WPF that I am binding to an object.

I have a DataGridCheckBoxColumn on there which I want the users to be able to go through and tick the ones they want. Problem is they have to click twice, once for selection then again to check/uncheck. How on earth do you turn this off, I've been searching for way to long to find the answer to this. The datagrid has SelectionMode and SelectionUnit properties - neither of which accept 'none' or 'go away'

Any help is appreciated! My code is below for reference

<my:DataGrid Margin="15"  Name="dgPreview" 
        AutoGenerateColumns="False" CanUserSortColumns="True" 
             CanUserDeleteRows="True" 
             Background="White" 
             ColumnHeaderHeight="20" 
             VerticalScrollBarVisibility="Visible" 
             RowDetailsVisibilityMode="Visible" 
             >

    <my:DataGrid.Columns>
        <my:DataGridCheckBoxColumn  MinWidth="50" Width="Auto" Header="Include" Binding="{Binding Include}" />
        <my:DataGridTextColumn MinWidth="50"  Width="Auto" Header="Override #" Binding="{Binding OverrideNumber}" />
        <my:DataGridTextColumn MinWidth="220" Width="*" Header="Name" Binding="{Binding Name}" />
        <my:DataGridTextColumn MinWidth="50" Width="Auto" IsReadOnly="True"  Header="Preview" Binding="{Binding Preview}" />
    </my:DataGrid.Columns>
</my:DataGrid>

Solution

  • The first click puts the cell in edit mode then the second click allows you to modify the checkbox. You can change this behavior by using a DataGridTemplateColumn instead of a DataGridCheckBoxColumn. Replace your DataGridCheckBoxColumn with this:

    <my:DataGridTemplateColumn MinWidth="50" Width="Auto" Header="Include" SortMemberPath="Include">
       <my:DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
             <CheckBox Style="{StaticResource DataGridCheckBoxStyle}" IsChecked="{Binding Path=Include}" />
          </DataTemplate>
       </my:DataGridTemplateColumn.CellTemplate>
    </my:DataGridTemplateColumn>
    

    DataGridCheckBoxStyle just makes the CheckBox look a little nicer in the DataGrid:

    <Style x:Key="DataGridCheckBoxStyle" TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}">
       <Setter Property="VerticalAlignment" Value="Center" />
       <Setter Property="Margin" Value="8,0,3,0" />
    </Style>