本文介绍了如何获取拥有ItemsControl内容的Panel实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个 ItemsControl 的内容都存储在面板中了吗?我们可以这样指定要在XAML中使用的面板:

Every ItemsControl has its content stored in Panel right ? We can specify the panel to be used in XAML like this:

<ListView Name="LView">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate >
            <StackPanel/>
        </ItemsPanelTemplate>
     </ListView.ItemsPanel>
</ListView>

我的问题是如何获取 Panel 在特定 ItemsControl ItemsPanel 属性(类型为 ItemsPanelTemplate )中使用的> / code>?例如,上述代码示例中的 ListView 名为 LView

My question is how to get instance of Panel that is used in the ItemsPanel property (of type ItemsPanelTemplate) of the particular ItemsControl ? For example ListView called LView from above code sample?

我无法使用 Name 属性或 x:Name ,这对于任何 ItemsControl 甚至使用默认 ItemsPanel 的人。

I cannot use Name property or x:Name, this must work for any ItemsControl even those using default ItemsPanel.

如果不清楚,请发表评论,认为有一个非常简单的解决方案。如果它看起来很复杂,那仅仅是因为我无法正确解释它。

In the case its not clear please comment, I think there is very simple solution. If it seems to be complicated that's only because I cannot explain it properly.

推荐答案

这有点棘手,因为您不知道面板的名称,因此您不能使用FindName等。这在存在 ItemsPresenter 的大多数情况下都可以使用

It's a little tricky since you don't know the name of the Panel so you can't use FindName etc. This will work for most cases where an ItemsPresenter is present

private Panel GetItemsPanel(DependencyObject itemsControl)
{
    ItemsPresenter itemsPresenter = GetVisualChild<ItemsPresenter>(itemsControl);
    Panel itemsPanel = VisualTreeHelper.GetChild(itemsPresenter, 0) as Panel;
    return itemsPanel;
}

GetVisualChild的实现

An implementation of GetVisualChild

private 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;
}

但是,并不总是使用ItemsPanel。请参阅伊恩·格里菲思(Ian Griffiths)的,以获得详细的解释。

However, the ItemsPanel isn't always used. See this answer by Ian Griffiths for a great explanation.

这篇关于如何获取拥有ItemsControl内容的Panel实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:52