如何获取ItemsPanel的实例?

时间:2013-03-29 21:33:33

标签: c# wpf

我正在编写自定义控件,我用

切换默认ItemsPanel
ItemsPanelProperty.OverrideMetadata(typeof(DataGrid),
    new FrameworkPropertyMetadata(new ItemsPanelTemplate(
    new FrameworkElementFactory(typeof(AdvancedVirtualizingStackPanel)))));

如何引用已创建AdvancedVirtualizingStackPanel的实例?

1 个答案:

答案 0 :(得分: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;
}