右键单击以选择ListBox中的项目

时间:2012-02-09 23:21:00

标签: c# winforms select listbox right-click

我正在尝试制作一个项目列表,您可以通过右键单击并启用上下文菜单来执行多项操作。我已经完成了,没有任何问题。

但我想拥有它,以便当您右键单击某个项目而不是选择当前项目时,选择鼠标所在的项目。

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

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

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

3 个答案:

答案 0 :(得分:34)

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

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

答案 1 :(得分:7)

这个正在运作......

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

}

答案 2 :(得分: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;
}