0
votes

My app have a DataGridCheckBoxColumn where the header is a checkbox. I am trying to Achieve the following functionalities:

  1. when user checks the header checkbox the whole column should be checked.
  2. when user uncheck the column header the whole DataGridCheckBoxColumn should be unchecked.
  3. when whole column is checked and user unchecks one single cell the header should also get unchecked.

Is it possible to achieve this functionality with out writing code behind?

Here is my code which i use to create the DataGridCheckbox column

 <DataGridCheckBoxColumn
     Binding="{Binding Path=IsSelected,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
     ElementStyle="{StaticResource DataGridCheckBoxStyle}" >
     <DataGridCheckBoxColumn.Header>
         <CheckBox
             IsChecked="{Binding Path=Data.AllItemsSelected, Source={StaticResource proxy}}"
             IsEnabled="{Binding Path=IsBusy, Converter={StaticResource BooleanNotConverter}}" />
     </DataGridCheckBoxColumn.Header>
 </DataGridCheckBoxColumn>

Thanks in advance

1

1 Answers

0
votes

Instead of using a column for a checkbox you should use DataGridRowHeader which is intended for purposes such as the SelectAll column.

<DataGrid>
    <DataGrid.RowHeaderTemplate>
        <DataTemplate>
            <CheckBox x:Name="selectCheckBox"
                      Margin="2,0,0,0"
                      IsChecked="{Binding Path=IsSelected, 
                                          Mode=TwoWay,
                                          RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGridRow}}}">
            </CheckBox>
        </DataTemplate>
    </DataGrid.RowHeaderTemplate>

    <DataGrid.CommandBindings>
        <CommandBinding Command="SelectAll" Executed="CommandBinding_Executed" />
    </DataGrid.CommandBindings>
</DataGrid>

By default, the header button will only act as a SelectAll button. To allow it to unselect DataGrid.CommandBindings is also declared to change the behaviour of the SelectAll button. In code behind, declare the following handler:

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    var dg = (DataGrid)sender;

    // You might want to do some null checking here

    // If all items are selected, then unselect all
    if (dg.SelectedItems.Count == dg.Items.Count)
        dg.UnselectAll();       
    else
        dg.SelectAll();

    e.Handled = true;
}