[英]ListBoxItem index on ListBox mouseover
I have a ListBox
in a WPF application that has a MouseMove
event handler attached. 我在WPF应用程序中有一个
ListBox
,它附加了一个MouseMove
事件处理程序。 What I would like to do is to use this event to get the index of the item the mouse is over. 我想要做的是使用此事件来获取鼠标结束的项目的索引。
Simplified example of my code: 我的代码的简化示例:
<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
}
I would try using ViusalHelper HitTest method for that, something like this : 我会尝试使用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);
}
}
Try this: 尝试这个:
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;
}
}
}
You can also try this much shorter option: 您还可以尝试这个更短的选项:
public void OnMouseMove(object sender, MouseEventArgs e)
{
int currentindex = MyList.Items.IndexOf(sender) ;
}
However I'm not too sure whether it will work with your method of binding. 但是我不太确定它是否适用于你的绑定方法。
Option 3:
选项3:
A little hacky but you could get the point value of the current location and then use IndexFromPoint
有点hacky,但你可以得到当前位置的点值,然后使用
IndexFromPoint
Eg: 例如:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.