在点击事件中查找按钮的父级ListViewItem

3

我有一个按钮,它是每个ListViewItem的最后一列。当按下该按钮时,我需要在点击事件中找到该按钮(发送者)的父列表视图项。

我尝试过:

ListViewItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as ListViewItem;

DiscoverableItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as DiscoverableItem;

发现项(DiscoverableItem)是列表视图绑定的类型。我尝试了所有不同的组合,但每个都返回 null。
谢谢, 梅森曼
1个回答

12

您可以使用VisualTreeHelper来获取某个元素的祖先视觉对象。当然,它仅支持GetParent方法,但我们可以实现一些递归方法或类似的方法来沿着树向上查找,直到找到所需类型的父级为止:

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;
}

那么你可以像这样使用该方法:
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){
   //...
}

1
谢谢!已测试并可用。我用它来查找用户控件的父级,但没有意识到listViewItem不是按钮的直接父级。+1和已接受。 - meisenman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接