0

我有一个ListBox.

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

如何做到这一点?

4

2 回答 2

0
listbox.Items.Cast<UIElement>().Where(x => x.IsVisible)
于 2012-05-09T18:45:38.320 回答
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>
...
于 2021-08-03T14:43:23.943 回答