c# code for select all checkbox in wpf datagrid

后端 未结 5 1541
一个人的身影
一个人的身影 2020-12-15 00:17

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.

5条回答
  •  一个人的身影
    2020-12-15 00:47

    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(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(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);
            }
        }
    

提交回复
热议问题