且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找Click事件按钮,家长的ListViewItem

更新时间:2023-09-29 19:48:22

您可以使用 VisualTreeHelper 来得到一些视觉元素的祖先。当然,这仅支持方法的getParent ,但直到父所需类型的发现,我们可以实现一些递归方法或类似的走了树的内容:

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