8

I need some c# code to select / deselect all checkboxes in a datagrid in WPF 3.5 framework. I would like to do this by clicking a single header checkbox in the grid.

Please help.

Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157

5 Answers5

6

This can be done declaratively. The following creates a checkbox column for each row and which can toggle row selections. The header of the checkbox column can be clicked to do a select all of the rows.

Relevant portions from the xaml

<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit">
    <toolkit:DataGrid Name="dataGrid" 
     ItemsSource="{Binding}" AutoGenerateColumns="True" 
     SelectionMode="Extended" CanResizeRows="False">
    <toolkit:DataGrid.RowHeaderTemplate>
       <DataTemplate>
           <Grid>
               <CheckBox IsChecked="{
                  Binding Path=IsSelected, 
                  Mode=TwoWay, 
                  RelativeSource={RelativeSource FindAncestor, 
                  AncestorType={x:Type toolkit:DataGridRow}}}"
            />
           </Grid>
       </DataTemplate>
    </toolkit:DataGrid.RowHeaderTemplate>
    </toolkit:DataGrid>
</Window>
Pradeep
  • 4,099
  • 4
  • 31
  • 45
5

Here is the sample datagrid we use in the .Net 4.0 XAML file:

<DataGrid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Name="dgMissingNames" ItemsSource="{Binding Path=TheMissingChildren}" Style="{StaticResource NameListGrid}" SelectionChanged="DataGrid_SelectionChanged">
    <DataGrid.Columns>
        <DataGridTemplateColumn CellStyle="{StaticResource NameListCol}">
            <DataGridTemplateColumn.HeaderTemplate>
                <DataTemplate>
                    <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" />
                </DataTemplate>                            
            </DataGridTemplateColumn.HeaderTemplate>
            <DataGridTemplateColumn.CellTemplate>                        
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=Checked, UpdateSourceTrigger=PropertyChanged}" Name="theCheckbox"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>                            
        </DataGridTemplateColumn>
        <DataGridTextColumn Binding="{Binding Path=SKU}" Header="Album" CellStyle="{StaticResource NameListCol}"/>
        <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" CellStyle="{StaticResource NameListCol}"/>
        <DataGridTextColumn Binding="{Binding Path=Pronunciation}" Header="Pronunciation" CellStyle="{StaticResource NameListCol}"/>
    </DataGrid.Columns>
</DataGrid>

Here is the codebehind:

private void HeadCheck(object sender, RoutedEventArgs e, bool IsChecked)
{
    foreach (CheckedMusicFile mf in TheMissingChildren)
    {
        mf.Checked = IsChecked;
    }
    dgMissingNames.Items.Refresh();
}

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    HeadCheck(sender, e, true);
}

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
    HeadCheck(sender, e, false);
}

TheMissingChildren is a simple object structure with some string properties and an ischecked boolean.

HTH.

Lance Cleveland
  • 3,098
  • 1
  • 33
  • 36
  • if you are not going to use the sender object or the routedeventargs in HeadCheck you shouldnt be passing them in –  Jul 04 '11 at 15:34
  • The `UpdateSourceTrigger=PropertyChanged` does help me. Thanks. – AechoLiu Mar 19 '13 at 02:22
2

This is based on someone else's source that I can't recall, but we use it to help find visual children of a type. It may not be the most efficient use for this scenario but it might help get you on the right track.

    public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is childItem)
                return (childItem)child;

            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
                return childOfChild;
        }
        return null;
    }

[Edit 4.16.09] Based on that, try out this method. Should find all CheckBoxes and change the state as provided, callable from your event handler on the Checked/Unchecked events.

   public static void CheckAllBoxes(DependencyObject obj, bool isChecked)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            // If a checkbox, change IsChecked and continue.
            if (obj is CheckBox)
            {
                ((CheckBox) obj).IsChecked = isChecked;
                continue;
            }

            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            CheckAllBoxes(child, isChecked);
        }
    }
Jeff Wain
  • 1,010
  • 8
  • 12
0
DataColumn dt = null;            
        for (int i = 0; i < dataGrid.Columns.Count; i++)
        {

     dt = new DataColumn("Column Name");

            dt.DataType = typeof(Boolean);
            dt.DefaultValue = false;
             dataTable.Add(dt);
        }

dataGied.DataContext = dataTable;



<Custom:DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ItemsSource="{Binding}" />                    

Well it is just a rough Idea, hope this works

AZ_
  • 21,688
  • 25
  • 143
  • 191
0

I would use the new databinding features in WPF. Give all of the checkboxes a one-way binding on their IsChecked property with the binding source being the master checkbox's IsChecked property.

Another option would be to use triggers

Jacob Adams
  • 3,944
  • 3
  • 26
  • 42