如何从列表框中获取项目容器(例如stackpanel)

本文关键字:例如 stackpanel 项目 获取 列表 | 更新日期: 2023-09-27 18:02:35

我有这样的代码

<ListBox x:Name="filterListBox" Height="60">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" 
                        VirtualizingStackPanel.VirtualizationMode="Standard"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel x:Name="TargetPanel">
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Background>
        <SolidColorBrush />
    </ListBox.Background>
</ListBox>

和我得到的第一个列表框项与这个

object item = filterListBox.ItemContainerGenerator.ContainerFromIndex(0);
ListBoxItem lbi = item as ListBoxItem;

现在我需要得到这个stackpanel称为"TargetPanel",但我不知道如何。

如何从列表框中获取项目容器(例如stackpanel)

遗憾的是,没有一个内置的方法可以通过简单的方法调用来实现这一点。然而,这很简单。通过对这个示例进行一些修改,您可以通过name:

获得DataTemplate的特定子节点。
// the call
var item = filterListBox.ItemContainerGenerator
               .ContainerFromIndex(0) as ListBoxItem;
var sp = FindVisualChild<StackPanel>(item, "TargetPanel");
// the variable sp should be set to the TargetPanel for the item now 

需要添加的代码(可能在"helper"类中):

using System.Windows.Media;   // for VisualTreeHelper
private static TChildItem FindVisualChild<TChildItem>(DependencyObject obj, 
    string matchName = "") where TChildItem : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
    var child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is TChildItem)
        {
            // match by name
        var childName = child.GetValue(FrameworkElement.NameProperty) as string;
        if (!string.IsNullOrWhiteSpace(matchName))
        {
                if (matchName == childName) 
                {
                return (TChildItem)child;
                }
        } 
            else 
            {
                return (TChildItem)child;
            }       
        }
        else
        {
        var childOfChild = FindVisualChild<TChildItem>(child, matchName);
        if (childOfChild != null)
        {
            return childOfChild;
        }
        }
    }
    return null;
}
相关文章: