I have a button as the last column of each ListViewItem. When the button is pressed, I need to find the buttons (senders) parent list view item in the click event.
I have tried:
ListViewItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as ListViewItem;
DiscoverableItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as DiscoverableItem;
DiscoverableItem being the type that the listview is bound to. I have tried all different combinations and each one returns null.
Thanks, Meisenman
You can use VisualTreeHelper to get an ancestor visual of some element. Of course it supports only the method GetParent but we can implement some recursive method or something similar to walk up the tree until the desired type of the parent is found:
public T GetAncestorOfType<T>(FrameworkElement child) where T : FrameworkElement
{
var parent = VisualTreeHelper.GetParent(child);
if (parent != null && !(parent is T))
return (T)GetAncestorOfType<T>((FrameworkElement)parent);
return (T) parent;
}
Then you can use that method like this:
var itemToCancel = GetAncestorOfType<ListViewItem>(sender as Button);
//more check to be sure if it is not null
//otherwise there is surely not any ListViewItem parent of the Button
if(itemToCancel != null){
//...
}
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