【发布时间】:2011-02-23 16:39:05
【问题描述】:
在我的应用程序中,我有一个DataGridView,用于配置一些选项。这个想法是您可以在第一列中输入您想要的任何文本,但是如果您右键单击它将为您提供明确支持的值。我需要这是一个文本框而不是下拉列表,因为我需要支持编辑无效(或旧)配置。
我想要的是用户在字段名称列中单击鼠标右键,并拥有一个上下文菜单,该菜单根据这是什么类型的配置而有效。因此,我编写了以下事件
private void grvFieldData_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
// If this is a right click on the Field name column, create a context menu
// with recognized options for that field
if (e.Button == MouseButtons.Right && grvFieldData.Columns[e.ColumnIndex].Name == "clmFieldName")
{
ContextMenu menu = new ContextMenu();
if (_supportedDataGrids.ContainsKey((cmbDataGrid.SelectedItem as DataGridFieldList).GridName))
{
// Loop through all the fields and add them to the context menu
List<string> fields = _supportedDataGrids[((cmbDataGrid.SelectedItem as DataGridFieldList).GridName)];
fields.Sort();
foreach (string field in fields)
menu.MenuItems.Add(new MenuItem(field));
// Make sure there is at least one field before displaying the context menu
if (menu.MenuItems.Count > 0)
menu.Show(this, e.Location, LeftRightAlignment.Right);
}
}
}
这“正确”工作,但上下文菜单出现在表单的顶部,而不是鼠标指针所在的位置。如果我将 Show() 调用更改为使用 DataGridView 而不是表单,我会遇到同样的问题,但它会出现在网格的左上角,而不是鼠标所在的位置。
奇怪的是,如果我将此事件更改为 MouseClick 事件(而不是 CellMouseclick 事件),一切正常,并且上下文菜单准确出现在鼠标指针所在的位置。这个选项的问题是用户可能没有右键单击当前选择的单元格,这意味着当他们单击菜单项时,所选单元格将被更改,而不是他们右键单击的单元格。
有人知道为什么使用CellMouseClick 创建的上下文菜单没有显示在正确的位置吗?
【问题讨论】:
标签: c# winforms contextmenu