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.
<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){
//...
}