WPF select all Datagrid Checkbox

Asked

Viewed 433 times

0

Hello, I’m trying to select all Checkbox of a datagrid but I’m not succeeding.

Below is my code to select:

private void CheckUnCheckAll(object sender, RoutedEventArgs e)
{
    CheckBox chkSelectAll = ((CheckBox)sender);
    if (chkSelectAll.IsChecked == true)
    {
        dgUsers.Items.OfType<CheckBox>().ToList().ForEach(x => x.IsChecked = true);
    }
    else
    {       
         dgUsers.Items.OfType<CheckBox>().ToList().ForEach(x => x.IsChecked = false);
    }
}

Where dgUsers is my Datagrid however I could notice that is not finding any checkbox inside the grid.

Below is my shampoo where creates the checkbox within the datagrid see that I invoke the function by clicking on the checkbox:

<DataGrid.Columns>
    <DataGridCheckBoxColumn x:Name="col0" HeaderStyle="{StaticResource ColumnHeaderGripperStyle}">
         <DataGridCheckBoxColumn.HeaderTemplate>
              <DataTemplate>
                   <CheckBox Click="CheckUnCheckAll" >
                   </CheckBox>
              </DataTemplate>
         </DataGridCheckBoxColumn.HeaderTemplate>
    </DataGridCheckBoxColumn>
<DataGrid.Columns>

Here’s a grid image

inserir a descrição da imagem aqui

What would be the correct way to select all the Checkboxes of a Datagrid?

1 answer

2


As soon as you search ?

//this event is for **Checked and UnChecked** of up check box (cbxall)
private void UpCheckbox_Checked(object sender, RoutedEventArgs e)
{
    //checkBox1 = cbxall (your up checkbox)
    if (checkBox1.IsChecked == true)
    {
        dataGrid1.Items.OfType<YourClass>().ToList().ForEach(x => x.IsChecked = true);
    }
    else
    {
        dataGrid1.Items.OfType<YourClass>().ToList().ForEach(x => x.IsChecked = false);
    }
}

//this event is for all other check box
//**Checked and UnChecked** of all other check box is this event
private void OtherCheckbox_Checked(object sender, RoutedEventArgs e)
{
    //checkBox1 = cbxall (your up checkbox)
    if (dataGrid1.Items.OfType<YourClass>().All(x => x.IsChecked == true))
    {
        checkBox1.IsChecked = true;
    }
    else if (dataGrid1.Items.OfType<YourClass>().All(x => x.IsChecked == false))
    {
        checkBox1.IsChecked = false;
    }
    else
    {
        checkBox1.IsChecked = null;
    }
}

Source

  • or the element I want in the Checkbox case ?

  • if I’m not mistaken Checkbox, if you check the code is similar to what you already have currently just adapt

  • Thanks after a search discover that where Yourclass is the Modelview that must be passed and isChecked is the name of the property that is defined in the modelview for the checkbox biding

Browser other questions tagged

You are not signed in. Login or sign up in order to post.