2016-08-23 81 views
1

我在附有MouseMove事件处理程序的WPF应用程序中有ListBox。我想要做的就是使用这个事件来获取鼠标所在物品的索引。我的代码ListBox上的ListBoxItem索引mouseover

简单的例子:

<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

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

} 
+0

工程非常好。由于OP使用'ListBox'而不是'ListView',所以在你的例子中'ListViewItem'的所有​​实例都应该改为'ListBoxItem'。 – Stewbob

+0

我的不好,我编辑为使用列表框 – Mathieu

+0

这似乎工作。我在VisualTreeHelper的周围挣扎着,但这让我正确地修复了它。 Ta:D –

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:

有点哈克但你可以得到当前位置的点值,然后使用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); 
} 
+0

不怕,发件人是ListBox,所以'sender as ListBoxItem'的转换是'null'。此外,比较不会得到列表中最后一项的正确索引,因为内容与对象参考比较相同。 –

+0

再一次响应你的编辑,发件人对象不是'ListBoxItem'我害怕,所以这也行不通。 –

+0

不幸的是,第三个选项只适用于'Windows.Forms.ListBox',而我正在使用'Windows.Controls.ListBox'与WPF内联。我试图看看TreeHelper类,但没有看到任何有用的东西。 –