0

我一直在尝试创建右键单击功能以在 C# 中显示上下文菜单,但它似乎不起作用。知道为什么吗?

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        ContextMenu m = new ContextMenu();
        m.MenuItems.Add(new MenuItem("Copy"));

        int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;

        m.Show(dataGridView1, new Point(e.X, e.Y));
    }
}
4

1 回答 1

1

我不确定你在使用什么,WPF/WinForms/BlackMagic/Etc ......但似乎每次右键单击你都会创建一个新的上下文菜单,它没有附加到任何东西......

ContextMenu MyMenu = new ContextMenu();
MyMenu.MenuItems.Add("Copy");

您应该将其附加到您正在使用的任何控件(在您的情况下,我认为是网格或行):

SomeGrid.ContextMenu = MyMenu;

在 WPF 中,在 ListBox 上使用一个看起来像

<ListBox x:Name="NameYourList"  
      ItemsSource="{Binding SomeItem}"
      SelectedItem="{Binding SomeProperty, UpdateSourceTrigger=PropertyChanged}"
      >
<ListBox.ContextMenu>
    <ContextMenu>
        <MenuItem Header ="Copy Me" Command="{Binding Copy_Command}" 
                  CommandParameter="{Binding SomeProperty}"
        />
    </ContextMenu>
</ListBox.ContextMenu>
于 2013-11-03T00:08:42.787 回答