Find Parent ListViewItem of button on Click Event

前端 未结 1 1593
南笙
南笙 2021-01-14 17:12

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.

<
相关标签:
1条回答
  • 2021-01-14 17:54

    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){
       //...
    }
    
    0 讨论(0)
提交回复
热议问题