How to determine the type of items in classes derived from ItemsControl

96 Views Asked by At

I am implementing an Attached Property for the ItemsControl. Faced with such a task that I cannot solve. I climb from the UI element in the ItemTemplate along the visual tree to the ItemsControl. There is no problem with that. But I also need to define the type used to generate items in the ItemsControl. And this type is also different in different classes derived from ItemsControl.

Let's say for ListBox can apply the following code

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

There are 0 best solutions below