Tuesday, September 9, 2014

WPF ListView , GridView Select All CheckBox Operations Full Example (Multi Select)

WPF ListView , GridView Select All CheckBox Operations Full Example

Lately i'm working on developing tool to improve my work productivity using WPF (Windows Presentation Foundation)

And i encounter a problem that i want to use GridView with  Check Box on the Header to Select All Rows "Items"





XAML Code :


 <ListView  Name="lstgrd" SelectionMode="Multiple" Margin="10,10,10,0" SelectionChanged="lstgrd_SelectionChanged" MouseDoubleClick="lstgrd_MouseDoubleClick" ScrollViewer.VerticalScrollBarVisibility="Visible"  ScrollViewer.HorizontalScrollBarVisibility="Visible"  ScrollViewer.CanContentScroll="True"  HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="119.263">
            <ListView.View>
                <GridView AllowsColumnReorder="true" ColumnHeaderToolTip="Authors">
                    <!-- Add a ContextMenu to GridView Header -->
                    <GridView.ColumnHeaderContextMenu>
                        <ContextMenu >
                            <MenuItem Header="Ascending" Click="MenuItem_Click" />
                            <MenuItem Header="Descending" />
                        </ContextMenu>
                    </GridView.ColumnHeaderContextMenu>
                    <!-- Add GridVeiw Columns -->
                    <GridViewColumn  Width="25">
                        <GridViewColumn.Header>
                            <CheckBox Name="chkWspSelectAll" HorizontalAlignment="Center" VerticalAlignment="Center" Checked="chkWspSelectAll_Checked"  Unchecked="chkWspSelectAll_Unchecked"  IsThreeState="False"/>
                        </GridViewColumn.Header>
                     
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Name="chkWspSelect" IsChecked="{Binding Path=IsSelected}" HorizontalContentAlignment="Center"  HorizontalAlignment="Center" VerticalAlignment="Center" Checked="chkWspSelect_Checked"  Unchecked="chkWspSelect_Unchecked"  IsThreeState="False"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Path=Name}" />
                    <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Path=Age}" />
                    <GridViewColumn Header="Mail" Width="150">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Mail}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>                  
                </GridView>
            </ListView.View>
        </ListView>




Code : 


 public partial class MainWindow : Window
    {
        private static List<User> items = new List<User>();
        public MainWindow()
        {
            InitializeComponent();
            //===============================          
            items.Add(new User() { Name = "NADY", Age = 31, Mail = "naadydev@gmail.com" });
            items.Add(new User() { Name = "Remoo", Age = 39, IsSelected = true, Mail = "Remoo@blabla.com" });
            items.Add(new User() { Name = "JanRio", Age = 7, Mail = "JanRio@blabla.com" });
            lstgrd.ItemsSource = items;
        }
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
          //Your Code Here
        }
        private void lstgrd_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ListView cmd = (ListView)sender;
            //User selectedItem = (User)(((System.Data.DataRowView)(cmd.SelectedItem)).Row[0]);
            //CheckBox chk = myDataGrid.Columns[0].GetCellContent(e.Row) as CheckBox;
            //chk.IsChecked = false;
            //checkboxes.Add(chk);
        }

        private void chkWspSelectAll_Checked(object sender, RoutedEventArgs e)
        {        
            individualChkBxUnCheckedFlag = false;
            //=====================
            foreach (User item in lstgrd.ItemsSource)
            {
                item.IsSelected = true;            
                lstgrd.SelectedItems.Add(item);                    
            }        
        }

        private void chkWspSelectAll_Unchecked(object sender, RoutedEventArgs e)
        {          
            if (!individualChkBxUnCheckedFlag)
            {
                foreach (User item in lstgrd.ItemsSource)
                {
                    item.IsSelected = false;
                    //int itemIndex = items.IndexOf(item);
                    lstgrd.SelectedItems.Remove(item);
                    //lstgrd.SelectedItems.Add(lstgrd.Items.GetItemAt(2));              
                }
            }
        }

        private void chkWspSelect_Checked(object sender, RoutedEventArgs e)
        {    
            ListBoxItem item = ItemsControl.ContainerFromElement(lstgrd, e.OriginalSource as DependencyObject) as ListBoxItem;
            if (item != null)
            {
                item.IsSelected = true;
            }        
        }

        private static bool individualChkBxUnCheckedFlag { get; set; }
        private void chkWspSelect_Unchecked(object sender, RoutedEventArgs e)
        {
            ListBoxItem item = ItemsControl.ContainerFromElement(lstgrd, e.OriginalSource as DependencyObject) as ListBoxItem;
            if (item != null)
                item.IsSelected = false;

            individualChkBxUnCheckedFlag = true;
            CheckBox headerChk = (CheckBox)((GridView)lstgrd.View).Columns[0].Header;
            headerChk.IsChecked = false;
        }

        private void lstgrd_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //User user = (User)e.AddedItems[0];
            //int itemIndex = items.IndexOf(xx);
            //VisualTreeHelper.GetChild()
            //lstgrd.ItemContainerGenerator.ContainerFromIndex
            //lstgrd.ItemContainerGenerator.ContainerFromItem
            //lstgrd.ItemContainerGenerator.IndexFromContainer
            //lstgrd.ItemContainerGenerator.ItemFromContainer
            if (e.AddedItems.Count > 0)
            {
                //------------
                User user = (User)e.AddedItems[0];
                ListViewItem lvi = (ListViewItem)lstgrd.ItemContainerGenerator.ContainerFromItem(user);
                CheckBox chkBx = FindVisualChild<CheckBox>(lvi);
                if (chkBx != null)
                    chkBx.IsChecked = true;
                //------------              
            }
            else // Remove Select All chkBox
            {
                User user = (User)e.RemovedItems[0];
                ListViewItem lvi = (ListViewItem)lstgrd.ItemContainerGenerator.ContainerFromItem(user);
                CheckBox chkBx = FindVisualChild<CheckBox>(lvi);
                if (chkBx != null)
                    chkBx.IsChecked = false;
            }
            //============                    
        }

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

                    T childItem = FindVisualChild<T>(child);
                    if (childItem != null) return childItem;
                }
            }
            return null;
        }
             
    }
    public class User
    {
        public string Name { get; set; }
        public bool IsSelected { get; set; }
        public int Age { get; set; }

        public string Mail { get; set; }
    }

4 comments:

Anonymous said...

Finally I found an example which was working and understandable.
Thx regards Jos

Avinash said...

Thank you Nandy, this is the solution I am looking for :)

Anonymous said...

Will it make the application simpler by setting the checkbox mode to two-way?

Anonymous said...

Excelente post! Justo lo que buscaba. Muchas gracias!