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 开发者_Python百科the ListView from the item itself.
I tried using the Parent property, but for some reason, it returns a StackPanel.
Any ideas?
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;
}
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
I recently discovered this concise solution:
ListView listView = ItemsControl.ItemsControlFromItemContainer(listViewItem) as ListView;
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!
精彩评论