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

时间:2014-05-08 13:45:56

标签: c# xaml windows-phone-8

我有这样的代码

<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;

现在我需要将这个堆栈面板称为&#34; TargetPanel&#34;但我不知道怎么做。你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

遗憾的是,没有一种内置方法可以通过简单的方法调用来实现。但是,这很容易。通过对this示例进行一些修改,您可以通过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 

你需要在某处添加的代码(它可能在“帮助者”类中):

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;
}