38

If i have a component derived from ItemsControl, can I access a collection of it's children so that I can loop through them to perform certain actions? I can't seem to find any easy way at the moment.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
James Hay
  • 12,580
  • 8
  • 44
  • 67

3 Answers3

66

A solution similar to Seb's but probably with better performance :

for(int i = 0; i < itemsControl.Items.Count; i++)
{
    UIElement uiElement =
        (UIElement)itemsControl.ItemContainerGenerator.ContainerFromIndex(i);
}
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
25

See if this helps you out:

foreach(var item in itemsControl.Items)
{
    UIElement uiElement =
        (UIElement)itemsControl.ItemContainerGenerator.ContainerFromItem(item);
}

There is a difference between logical items in a control and an UIElement.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Seb Nilsson
  • 26,200
  • 30
  • 103
  • 130
23

To identify ItemsControl's databound child controls (like a ToggleButton), you can use this:

for (int i = 0; i < yourItemsControl.Items.Count; i++)
{

    ContentPresenter c = (ContentPresenter)yourItemsControl.ItemContainerGenerator.ContainerFromItem(yourItemsControl.Items[i]);
    ToggleButton tb = c.ContentTemplate.FindName("btnYourButtonName", c) as ToggleButton;

    if (tb.IsChecked.Value)
    {
        //do stuff

    }
}
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161
  • 4
    You need to call `c.ApplyTemplate();` before calling `FindName()` or else it returns null. – Karmacon Jan 15 '16 at 00:00
  • 2
    This should be the accepted answer in my opinion. Anyway the c variable must be checked because it can be null, for example if the control is not visible. – Emanuele Benedetti Nov 15 '18 at 14:56