C# 如何访问 ItemsControl 的子项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1000345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:13:12  来源:igfitidea点击:

How do I access the children of an ItemsControl?

c#wpfitemscontrol

提问by James Hay

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.

如果我有一个从 派生的组件ItemsControl,我是否可以访问它的子组件的集合,以便我可以遍历它们以执行某些操作?我目前似乎找不到任何简单的方法。

采纳答案by Thomas Levesque

A solution similar to Seb'sbut probably with better performance :

类似于Seb 的解决方案,但可能具有更好的性能:

for(int i = 0; i < itemsControl.Items.Count; i++)
{
    UIElement uiElement =
        (UIElement)itemsControl.ItemContainerGenerator.ContainerFromIndex(i);
}

回答by Neil Barnwell

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

我假设ItemsControl.Items[index]不起作用,然后?

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.

我不是在开玩笑,我也没有检查过自己——这只是我的第一个猜测。大多数情况下,控件将具有项目索引器属性,即使它是数据绑定的。

回答by Seb Nilsson

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.

控件中的逻辑项与UIElement.

回答by Junior Mayhé

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

要识别ItemsControl的数据绑定子控件(如 a ToggleButton),您可以使用:

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

    }
}