【问题标题】:ListBoxItem index on ListBox mouseoverListBox 鼠标悬停时的 ListBoxItem 索引
【发布时间】:2016-12-30 12:56:51
【问题描述】:

我在 WPF 应用程序中有一个 ListBox,它附加了一个 MouseMove 事件处理程序。我想做的是使用这个事件来获取鼠标所在项目的索引。

我的代码的简化示例:

<StackPanel>
    <ListBox x:Name="MyList" MouseMove="OnMouseMove"/>
    <Separator/>
    <Button>Beep</Button>
</StackPanel>
public CodeBehindConstructor()
{
   List<string> list = new List<string>();
   list.Add("Hello");
   list.Add("World");
   list.Add("World"); //Added because my data does have duplicates like this

   MyList.ItemsSource = list;
}

public void OnMouseMove(object sender, MouseEventArgs e)
{
   //Code to find the item the mouse is over
}

【问题讨论】:

    标签: c# wpf xaml listbox


    【解决方案1】:

    我会尝试使用 ViusalHelper HitTest 方法,如下所示:

    private void listBox_MouseMove(object sender, MouseEventArgs e)
    {
        var item = VisualTreeHelper.HitTest(listBox, Mouse.GetPosition(listBox)).VisualHit;
    
        // find ListViewItem (or null)
        while (item != null && !(item is ListBoxItem))
            item = VisualTreeHelper.GetParent(item);
    
        if (item != null)
        {
            int i = listBox.Items.IndexOf(((ListBoxItem)item).DataContext);
            label.Content = string.Format("I'm on item {0}", i);
        }
    
    }
    

    【讨论】:

    • 效果很好。由于 OP 使用的是 ListBox 而不是 ListView,因此您示例中的所有 ListViewItem 实例都应更改为 ListBoxItem
    • 这似乎有效。我在 VisualTreeHelper 上苦苦挣扎,但这让我能够立即修复它。塔:D
    【解决方案2】:

    试试这个:

    public void OnMouseMove(object sender, MouseEventArgs e)
    {
            int currentindex;
            var result = sender as ListBoxItem;
    
            for (int i = 0; i < lb.Items.Count; i++)
            {
                if ((MyList.Items[i] as ListBoxItem).Content.ToString().Equals(result.Content.ToString()))
                {
                    currentindex = i;
                    break;
                }
            }
    }
    

    你也可以试试这个更短的选项:

    public void OnMouseMove(object sender, MouseEventArgs e)
    {
        int currentindex = MyList.Items.IndexOf(sender) ;
    }
    

    但是我不太确定它是否适用于您的绑定方法。

    选项 3:

    有点hacky,但你可以获取当前位置的点值,然后使用IndexFromPoint

    例如:

    public void OnMouseMove(object sender, MouseEventArgs e)
    {
        //Create a variable to hold the Point value of the current Location
        Point pt = new Point(e.Location);
        //Retrieve the index of the ListBox item at the current location. 
        int CurrentItemIndex = lstPosts.IndexFromPoint(pt);
    }
    

    【讨论】:

    • 不怕,发件人是ListBox,所以转换sender as ListBoxItem就是null。此外,由于内容等于对象引用比较,因此比较不会得到列表中最后一项的正确索引。
    • 再次响应您的编辑,恐怕发件人对象不是ListBoxItem,所以这也行不通。
    • 不幸的是,第三个选项仅适用于 Windows.Forms.ListBox,而我使用 Windows.Controls.ListBox 与 WPF 内联。我正在尝试查看 TreeHelper 类,但没有看到任何有用的东西。
    猜你喜欢
    • 2017-07-17
    • 1970-01-01
    • 2012-04-13
    • 2011-08-04
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    相关资源
    最近更新 更多