【问题标题】:How to get Item under cursor in WPF ListView如何在 WPF ListView 中获取光标下的项目
【发布时间】:2019-03-29 01:12:16
【问题描述】:

如何在 ListView 中获取光标下的项目?

例如,当我移动鼠标光标时,我希望在它(光标)下获取一个项目并将其名称放在状态栏上。

实际上我需要 WinForms.NET 中的 GetItemAt(int x,int y) 之类的方法

谢谢!

UPD:已找到答案。观看下面的扩展方法

【问题讨论】:

    标签: wpf listview


    【解决方案1】:

    您可以尝试使用 VisualTreeHelper.HitTest 方法。像这样的:

        System.Windows.Point pt = e.GetPosition(this);
        System.Windows.Media.VisualTreeHelper.HitTest(this, pt);
    

    【讨论】:

    • 谢谢!使用您的代码,我做了一个小的扩展方法。我希望有人会觉得它有用
    【解决方案2】:
    public static object GetObjectAtPoint<ItemContainer>(this ItemsControl control, Point p)
    where ItemContainer : DependencyObject
    {
        // ItemContainer - can be ListViewItem, or TreeViewItem and so on(depends on control)
        ItemContainer obj = GetContainerAtPoint<ItemContainer>(control, p);
        if (obj == null)
            return null;
    
        return control.ItemContainerGenerator.ItemFromContainer(obj);
    }
    
    public static ItemContainer GetContainerAtPoint<ItemContainer>(this ItemsControl control, Point p)
    where ItemContainer : DependencyObject
    {
        HitTestResult result = VisualTreeHelper.HitTest(control, p);
        DependencyObject obj = result.VisualHit;
    
        while (VisualTreeHelper.GetParent(obj) != null && !(obj is ItemContainer))
        {
            obj = VisualTreeHelper.GetParent(obj);
        }
    
        // Will return null if not found
        return obj as ItemContainer; 
    }
    

    【讨论】:

    • 嗨,Grigory,请帮忙,我想做你所做的,但是当我粘贴两个函数时,我得到了这个错误:“扩展方法必须在非泛型中定义”
    • 嗨,阅读一些关于 C# 中的扩展方法的文章或书籍。基本面相当重要。如果要更多地解决这个问题 - 你必须把这个方法放到一个静态类中。
    • @YMELS 不要在泛型类中声明扩展方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多