How to Add Select All Checkbox in Xamgrid using WPF and MVVM

Shikha Gupta
SharePoint Developer
Published On :   10 Apr 2017
Visit Count
Today :  2    Total :   2644

In the second part we saw that how we can select specific rows and add the copied of that rows. Now we will have header checkbox column where when selecting it all the rows will be selected and on deselecting it all the rows will be deselected.

Let’s modify the previous solution.

1. Open MainWindow.Xaml and before <ig:TemplateColumn.ItemTemplate> add the following code.

          <CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ig:XamGrid}}, Path=DataContext.AreAllChecked}" Content=""/>

The screen will look like below:


2. Now we have to create AreAllCheckproperty. Open XamgridViewModel.cs and copy and paste the following:

 private bool? areAllChecked;
         public bool? AreAllChecked
             get { return areAllChecked; }
                 if (value == true)
                     foreach (var row in DataEditorDataTable.Rows)
                         ((DataRow)row)["Select"] = true;
                 else if (value == false)
                     foreach (var row in DataEditorDataTable.Rows)
                         ((DataRow)row)["Select"] = false;
                 areAllChecked = value;

3. Now run the project and when you check the header check box then all the rows will be checked and on clicking on Import button all the compid will be added to the list box.


Note: But there is still one issue that if we uncheck any rows then the header checkbox should be checked and if we manually check all the rows then the header check box should be checked.

So here we have uncheck a row and on doing that the header checkbox is still checked but it should be unchecked.clip_image006

4. In order to solve the above mentioned issue we are going to implement and datatable column changed event. In order to do so add the below code in the last line of Binddata() method.

DataEditorDataTable.ColumnChanged += DataEditorDataTable_ColumnChanged;

5. Add the following code to implement this column changed event.

 void DataEditorDataTable_ColumnChanged(object sender, DataColumnChangeEventArgs e)
             if (e.Column.ColumnName == "Select")
                 areAllChecked = true;
                 foreach (var row in DataEditorDataTable.DefaultView)
                     DataRowView rowView = (DataRowView)row;
                     if (rowView["Select"] != DBNull.Value)
                         var isSelected = (bool)rowView["Select"];
                         if (!isSelected)
                             areAllChecked = false;
                 // notify the UI that it should update bindings on the AreAllChecked property

The screen should look like below.


6. Now run the project and issue is solved.


Happy CodingJ