2016-08-23 79 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類,但沒有看到任何有用的東西。 –