【问题标题】:Right Click to select items in a ListBox右键单击以选择列表框中的项目
【发布时间】:2012-03-02 11:49:23
【问题描述】:

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

但我想拥有它,这样当您右键单击一个项目时,而不是让当前项目处于选中状态,而是选择鼠标悬停的项目。

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

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

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

【问题讨论】:

  • 这看起来像是 System.Windows.Forms.ListBox 中的错误,我们应该向 Microsoft 报告。

标签: c# winforms select listbox right-click


【解决方案1】:

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

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

【讨论】:

  • 如果上下文菜单已经绑定到列表框,只需使用: private void listBoxItems_MouseDown(object sender, MouseEventArgs e) { listBoxItems.SelectedIndex = listBoxItems.IndexFromPoint(e.X, e.Y); }
【解决方案2】:

这个正在工作...

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

}

【讨论】:

  • 刚刚替换了这一行 listBox.Items[index]; .SelectedIndex = 索引;这非常有效。
  • 奇怪的是点击事件似乎没有捕获右键或中间按钮。必须使用 MouseUp 来捕捉它们..
【解决方案3】:

也可以通过在整个列表框上设置 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;
}

【讨论】:

    猜你喜欢
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多