How do I access the children of an ItemsControl?

后端 未结 4 1066
悲&欢浪女
悲&欢浪女 2020-12-05 17:22

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\

相关标签:
4条回答
  • 2020-12-05 18:03

    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
    
        }
    }
    
    0 讨论(0)
  • 2020-12-05 18:10

    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);
    }
    
    0 讨论(0)
  • 2020-12-05 18:16

    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.

    0 讨论(0)
  • 2020-12-05 18:17

    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.

    0 讨论(0)
提交回复
热议问题