首页 > 解决方案 > 如何确定从 ItemsControl 派生的类中的项目类型

问题描述

我正在为 ItemsControl 实现一个附加属性。面对这样一个我无法解决的任务。我从 ItemTemplate 中的 UI 元素沿着可视化树爬到 ItemsControl。没有问题。但我还需要在 ItemsControl 中定义用于生成项目的类型。而且这个类型在ItemsControl派生的不同类中也有所不同。

假设 ListBox 可以应用以下代码

    public static bool GetIndexOn(FrameworkElement element)
    {
        int? index = (int?)element.GetValue(IndexProperty);
        if (index == null)
        {
            FrameworkElement parent = element;

            // Search ListBoxItem
            // But I need to find any type used to generate Item
            while (!(parent is System.Windows.Controls.ListBoxItem || parent == null))
                parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;

            if (parent == null)
                return false;

            // Saving the ListBoxItem
            System.Windows.Controls.ListBoxItem listBoxItem = (System.Windows.Controls.ListBoxItem)parent;


            // Search ItemsControl
            while (!(parent is ItemsControl || parent == null))
                parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;

            if (parent == null)
                return false;

            // Saving the ListBox
            ItemsControl listBox = (ItemsControl)parent;

            // Retrieving and storing index of ListBoxItem in ListBox
            index = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);
            element.SetValue(IndexPropertyKey, index);
        }
        return false;
    }

标签: c#wpfitemscontrolattached-propertiesitemcontainergenerator

解决方案


推荐阅读