Luke
Luke

Reputation: 2486

Is there any way to get at the items inside a UIElementCollection?

I have a bunch of CheckBoxes in a grid. I want to access them so that I can set them to checked or unchecked according to a registry value on start up.

I have got the Grid's children as a UIElementCollection, and Filtered out other Types.. However, there doesn't seem to be any way of accessing the data stored inside the collection. Is there an easy way of doing this?

Upvotes: 1

Views: 6122

Answers (2)

sll
sll

Reputation: 62544

To simplify search of controls by type or whatever you can use VisualTreeHelper and traverse elements in this way:

foreach (UIElement childElement in myUIElementCollection) 
{
  for (int i = 0; i < VisualTreeHelper.GetChildrenCount(childElement); i++)
  {
     DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
     var checkBox = child as CheckBox;
     if (checkBox != null)
     {
         // update it
     }
  }
}

BTW, why just not to expose boolean property like IsRegistryValueFound and just bind it to CheckBox.IsChecked property in XAML?

Upvotes: 1

Robert Levy
Robert Levy

Reputation: 29083

UIElementCollection is IEnumerable so you can just loop over it...

foreach( UIElement child in myUIElementCollection)
{
}

Upvotes: 7

Related Questions