How do I access the children of an ItemsControl?

Go To StackoverFlow.com

24

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.

2009-06-16 09:06
by James Hay


48

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);
}
2009-06-16 09:42
by Thomas Levesque
+1, thanks even though simple it solved my proble - DROP TABLE users 2013-06-11 13:31
it seems if the control hasn't rendered/been shown yet, it won't have any items - Maslow 2017-10-19 14:00


21

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.

2009-06-16 09:31
by Seb Nilsson


12

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

    }
}
2009-12-09 20:11
by Junior M
You need to call c.ApplyTemplate(); before calling FindName() or else it returns null - Karmacon 2016-01-15 00:00
@Karmacon Works fine without c.ApplyTemplate(); for me.. - rumblefx0 2016-09-16 12:54
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 2018-11-15 14:56


0

I'm assuming ItemsControl.Items[index] doesn't work, then?

I'm not being funny, and I haven't checked for myself - that's just my first guess. Most often a control will have an items indexer property, even if it's databound.

2009-06-16 09:11
by Neil Barnwell
This doesn't retrieve the "child" elements (controls), only the items of the list, which are not necessarily controls - Thomas Levesque 2009-06-16 09:43
No if, you use a data source and a data template, e.g. a load of strings to use in a data template, you get the string returned as the item - James Hay 2009-06-16 09:45
Fair enough. I'll leave my answer on as your comments might be useful - Neil Barnwell 2009-06-16 15:37