Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the children of an ItemsControl?

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.

like image 586
James Hay Avatar asked Jun 16 '09 09:06

James Hay


3 Answers

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);
}
like image 76
Thomas Levesque Avatar answered Sep 19 '22 07:09

Thomas Levesque


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.

like image 23
Seb Nilsson Avatar answered Sep 19 '22 07:09

Seb Nilsson


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

    }
}
like image 38
Junior Mayhé Avatar answered Sep 19 '22 07:09

Junior Mayhé