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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With