Right Click to select items in a ListBox

回眸只為那壹抹淺笑 提交于 2019-11-30 10:59:40
demoncodemonkey

Handle ListBox.MouseDown and select the item in there. Like this:

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

this one is working...

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

}

Can also get same behaviour by setting a MouseRightButtonUp event on the whole listbox then:

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!