How to get ListView from ListViewItem?

I have a ListViewItem that is added to the ListView, but I don’t know which listView List is added to.

I would like (via ListViewItem) to grab the ListView from the element itself.

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

Any ideas?

+5
source share
4 answers

I got 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;
    }
+5
source

Although this is a rather old question, it does not work for WinRT

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

+4
source

, , .

I have only a few ListView controls (two or three), so I can do the following.

ListViewItem listViewItem = e.OriginalSource as ListViewItem;
if (listViewItem == null)
{
    ...
}
else
{
    if (firstListView.ItemContainerGenerator.IndexFromContainer(listViewItem) >= 0)
    {
        ...
    }
    else if (secondListView.ItemContainerGenerator.IndexFromContainer(listViewItem) >= 0)
    {
        ...
    }
}

This can be used with a foreach loop, but if there are hundreds of ListView controls to iterate, then finding the parent ListView in the ListViewItem is probably more efficient (like most other answers). However, I find that my solution is cleaner (a bit). Hope this helps someone!

0
source

I recently found this short solution:

ListView listView = ItemsControl.ItemsControlFromItemContainer(listViewItem) as ListView;
0
source

All Articles