ListBox ...获取UI中可见的所有子项? WPF

时间:2012-05-09 18:15:07

标签: c# wpf listbox

我有ListBox

我需要获取UI中可见的所有项目的列表。

如何做到这一点?

2 个答案:

答案 0 :(得分:0)

listbox.Items.Cast<UIElement>().Where(x => x.IsVisible)

答案 1 :(得分:0)

要获取所有控件,请使用此代码

foreach (var item in list.Items)
{
     var myContentPresenter = FindVisualChild<ContentPresenter>(list.ItemContainerGenerator.ContainerFromItem(item));
     DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
     TextBox tb = (TextBox)myDataTemplate.FindName("tb", myContentPresenter);
}

FindVisualChild 方法:

 private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                {
                    return (childItem)child;
                }
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }

XAML 看起来像这样:

...
<ListBox Name="list">
    <ListBox.ItemTemplate>
         <DataTemplate>
              <TextBox x:Name="tb"/>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
...