How to get a ListView from a ListViewItem?

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?

Upvotes: 5

Views: 6504

Answers (4)

fyodorfranz
fyodorfranz

Reputation: 486

I recently discovered this concise solution:

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

Upvotes: 4

Kohányi Róbert
Kohányi Róbert

Reputation: 10141

I'm using an approach different from those that were already suggested.

I only have a handful of 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 could be used with a foreach loop but if there are hundreds of ListView controls to iterate through then looking up the parent ListView of the ListViewItem is probably more efficient (as most of the other answers suggest). However I think my solution is cleaner (a bit). Hope it helps someone!

Upvotes: 0

Anthony Wieser
Anthony Wieser

Reputation: 4611

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

Upvotes: 4

T. Webster
T. Webster

Reputation: 10109

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

Upvotes: 4

Related Questions