好的,我会自己回答。
首先你需要得到ItemsPresenter
. 您可以使用以下代码:
ItemsPresenter itemsPresenter =
(ItemsPresenter)GetTemplateChild(ItemsPresenterTemplateName);
// You have to name ItemsPresenter (using value of
// ItemsPresenterTemplateName string) in your XAML
然后:
itemsPresenter.ApplyTemplate(); // In case template is not applied yet
_stackPanel =
Helper.GetVisualChild<AdvancedVirtualizingStackPanel>(itemsPresenter);
你得到了你的面板。代码Helper.GetVisualChild()
:
public static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}