查找Click事件按钮,家长的ListViewItem [英] Find Parent ListViewItem of button on Click Event

查看:166
本文介绍了查找Click事件按钮,家长的ListViewItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮作为各ListViewItem的的最后一列。当按钮为pressed,我需要找到按钮(发件人)在click事件父列表视图项。

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.

我曾尝试:

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

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

DiscoverableItem在于列表视图绑定到的类型。我已经尝试了所有不同的组合,每一个返回null。

DiscoverableItem being the type that the listview is bound to. I have tried all different combinations and each one returns null.

谢谢,
Meisenman

Thanks, Meisenman

推荐答案

您可以使用 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){
   //...
}

这篇关于查找Click事件按钮,家长的ListViewItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆