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