Find parent ListViewItem of button in Click event
I have a button as the last column of each ListViewItem. When the button is clicked I need to find the list item of the parent list of buttons (senders) in the click event.
I tried:
ListViewItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as ListViewItem;
DiscoverableItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as DiscoverableItem;
DiscoverableItem is the type to which the list is bound. I've tried all different combinations and each one returns null.
Thanks, Meisenman
+3
source to share
1 answer
You can use VisualTreeHelper
to get a representation of the ancestor of some element. Of course, it only supports a method GetParent
, but we can implement some recursive method or something similar to walk up the tree until the desired parent type 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 this 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){
//...
}
+7
source to share