Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Parent ListViewItem of button on Click Event

Tags:

c#

listview

wpf

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

like image 311
meisenman Avatar asked Dec 02 '25 21:12

meisenman


1 Answers

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){
   //...
}
like image 86
King King Avatar answered Dec 04 '25 12:12

King King



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!