簡體   English   中英

如何從列表框中獲取項目容器(例如stackpanel)

[英]How to get item container (e.g. stackpanel) from listbox

我有這樣的代碼

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

現在,我需要獲得一個名為“ TargetPanel”的堆棧面板,但我不知道如何。 你能幫忙嗎?

不幸的是,沒有通過簡單的方法調用來執行此操作的內置方法。 但是,這很容易。 通過對該示例進行一些修改,您可以按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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM