C# 如何从列表框中获取项目容器(例如stackpanel)
我有这样的代码C# 如何从列表框中获取项目容器(例如stackpanel),c#,xaml,windows-phone-8,C#,Xaml,Windows Phone 8,我有这样的代码 <ListBox x:Name="filterListBox" Height="60"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" VirtualizingStackPanel.VirtualizationMode="Stand
<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>
现在我需要一个名为TargetPanel的stackpanel,但我不知道怎么做。您能帮忙吗。不幸的是,没有一种内置的方法可以通过简单的方法调用来实现这一点。然而,这很容易。通过对示例进行一些修改,您可以按名称获取DataTemplate的特定子级: 需要添加的代码可能位于帮助器类中:
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;
}
// 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;
}