Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a ListView from a ListViewItem?

Tags:

wpf

I've got a ListViewItem that is added to a ListView, but I don't know which ListView it is added to.

I would like to (through the ListViewItem) to be able to grab the ListView from the item itself.

I tried using the Parent property, but for some reason, it returns a StackPanel.

Any ideas?

like image 505
Mathias Lykkegaard Lorenzen Avatar asked Jan 22 '11 19:01

Mathias Lykkegaard Lorenzen


People also ask

What is a ListView item?

The ListViewItem class defines the appearance, behavior, and data associated with an item that is displayed in the ListView control. ListViewItem objects can be displayed in the ListView control in one of four different views. Items can be displayed as large or small icons or as small icons in a vertical list.


2 Answers

I've gotten this to run and work:

private void Window_Loaded(object s, RoutedEventArgs args)
    {
        var collectionview = CollectionViewSource.GetDefaultView(this.listview.Items);
        collectionview.CollectionChanged += (sender, e) =>
        {
            if (e.NewItems != null && e.NewItems.Count > 0)
            {                   
                var added = e.NewItems[0];
                ListViewItem item = added as ListViewItem;
                ListView parent = FindParent<ListView>(item);
            }
        };

    }   
    public static T FindParent<T>(FrameworkElement element) where T : FrameworkElement
    {
        FrameworkElement parent = LogicalTreeHelper.GetParent(element) as FrameworkElement;

        while (parent != null)
        {
            T correctlyTyped = parent as T;
            if (correctlyTyped != null)
                return correctlyTyped;
            else
                return FindParent<T>(parent);
        }

        return null;
    }
like image 116
T. Webster Avatar answered Oct 07 '22 10:10

T. Webster


While this is quite an old question, it doesn't work for WinRT

For WinRT, you need to traverse the Visual Tree using VisualTreeHelper instead of LogicalTreeHelper to find the ListView from the ListViewItem

like image 4
Anthony Wieser Avatar answered Oct 07 '22 08:10

Anthony Wieser