0

我正在编写自定义控件,在其中切换默认ItemsPanel

ItemsPanelProperty.OverrideMetadata(typeof(DataGrid),
    new FrameworkPropertyMetadata(new ItemsPanelTemplate(
    new FrameworkElementFactory(typeof(AdvancedVirtualizingStackPanel)))));

如何获得对 created 实例的引用AdvancedVirtualizingStackPanel

4

1 回答 1

0

好的,我会自己回答。

首先你需要得到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;
}
于 2013-03-30T19:31:42.440 回答