tags:

views:

295

answers:

5

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.

Cheers J

A: 

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.

Neil Barnwell
This doesn't retrieve the "child" elements (controls), only the items of the list, which are not necessarily controls.
Thomas Levesque
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
Fair enough. I'll leave my answer on as your comments might be useful.
Neil Barnwell
A: 

Use the ItemsControl.Items property:

foreach (var item in itemsControl1.Items)
{
    Console.WriteLine(item.ToString());
}
Oskar
To repeat my comment, 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
Well, then you should go with Seb's solution
Oskar
+4  A: 

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.

Seb Nilsson
+3  A: 

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);
}
Thomas Levesque
A: 

To identify itemscontrol's databinded 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

    }
}
Junior Mayhé