【问题标题】:Find Parent ListViewItem of button on Click Event在单击事件上查找按钮的父 ListViewItem
【发布时间】:2014-10-01 15:02:01
【问题描述】:

我有一个按钮作为每个 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。

谢谢, 梅森曼

【问题讨论】:

    标签: c# wpf listview


    【解决方案1】:

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

    【讨论】:

    • 谢谢!测试和工作。我用它来查找用户控件的父级,但没有意识到 listViewItem 不是按钮的直接父级。 +1 并接受
    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2018-12-18
    • 1970-01-01
    相关资源
    最近更新 更多