右键单击选择一个ListBox中的项目

28

我想制作一个项目列表,可以通过右键单击并弹出上下文菜单执行多个操作。这方面我已经完成了,没有任何问题。

但是,当你右键单击某个项目时,我希望选中鼠标悬停的项目而不是保留当前选定的项目。

我已经研究了这个问题和其他相关问题,并尝试使用indexFromPoint(通过我的研究找到),但每当我右键单击项时,它总是清除所选项目并且不显示上下文菜单,因为我已将其设置为仅当有所选项目时才出现。

这是我目前正在使用的代码:

ListBox.SelectedIndex = ListBox.IndexFromPoint(Cursor.Position.X, Cursor.Position.Y);

这似乎是 System.Windows.Forms.ListBox 中的一个错误,我们应该向微软报告它。 - Colonel Panic
3个回答

45

处理 ListBox.MouseDown 事件并选择其中的项。就像这样:

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
    listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
}

4
如果上下文菜单已绑定到列表框,请使用以下方法: private void listBoxItems_MouseDown(object sender, MouseEventArgs e) { listBoxItems.SelectedIndex = listBoxItems.IndexFromPoint(e.X, e.Y); } - Rustam Irzaev

12

这个可以工作...

this.ListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.List_RightClick);

private void List_RightClick(object sender, MouseEventArgs e)
{

    if (e.Button == MouseButtons.Right)
    {
        int index = this.listBox.IndexFromPoint(e.Location);
        if (index != ListBox.NoMatches)
        {
            listBox.Items[index];
        }
    }

}

1
我只是用 .SelectedIndex = index; 替换了这行代码 listBox.Items[index];,现在它完美地工作了。 - Mr. B
3
奇怪的是click事件似乎无法捕获正确的按钮或中间按钮,必须使用MouseUp来捕获它们。 - MattCochrane

0

也可以通过在整个列表框上设置MouseRightButtonUp事件来获得相同的行为:

private void AccountItemsT33_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    // If have selected an item via left click, then do a right click, need to disable that initial selection
    AccountItemsT33.SelectedIndex = -1;
    VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), (sender as ListBox)).OfType<ListBoxItem>().First().IsSelected = true;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接