private void StackPanel_Tap(object sender, TappedRoutedEventArgs e)
{
//获取到的对象是ListBoxItem
ListBoxItem myListBoxItem = (ListBoxItem)(listbox.ItemContainerGenerator.ContainerFromItem((sender as Panel).DataContext));
// 在ListBoxItem中查找ContentPresenter
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
……//省略若干代码
}
//查找可视化树某个类型的元素
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;
}