ListBox鼠标悬停上的ListBoxItem索引

时间:2016-08-23 15:43:11

标签: c# wpf xaml listbox

我在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
}

2 个答案:

答案 0 :(得分:3)

我会尝试使用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);
    }

}

答案 1 :(得分:0)

试试这个:

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

E.g:

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