将“右键单击”选项添加到“仅针对选定项目的每个项目的列表视图”中
本文关键字:项目 列表 视图 右键单击 单击 右键 选项 添加 | 更新日期: 2023-09-27 18:24:21
我有一个项目的列表视图,我希望这样,当用户右键单击其中一个项目时,它会显示一个上下文菜单,其中包含一些用户可以执行的选项或任务,但我希望它只在右键单击项目时显示上下文菜单,而不是空白。有这样的设置吗?
你必须自己做这件事。这有点痛。基本流程是。。。
- 创建一个名为contextMenuAllowed的全局布尔值
- 订阅
ListView
的MouseDown
事件。使用鼠标坐标(e.X和e.Y)在ListView
上执行HitTest
。如果他们点击了一个项目,并且是右键单击,请将contextMenuAllowed设置为true - 订阅
ListView
的MouseUp
事件。如果是鼠标右键,请将contextMenuAllowed设置为false - 订阅
ContextMenu
/ContextMenuStrip
的Opening
事件。如果contextMenuAllowed为false,则将e.Cancel设置为true并返回。这是阻止上下文菜单实际打开
这有点痛苦,但很容易做到,用户永远不会知道其中的区别。
这里有一个例子,我刚刚制作了一个新的自定义控件,它将完全符合您的要求:
using System;
using System.Windows.Forms;
public class CustomListView : ListView
{
private bool contextMenuAllowed = false;
public override ContextMenuStrip ContextMenuStrip
{
get
{
return base.ContextMenuStrip;
}
set
{
base.ContextMenuStrip = value;
base.ContextMenuStrip.Opening += ContextMenuStrip_Opening;
}
}
public CustomListView()
{
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ListViewHitTestInfo lvhti = HitTest(e.X, e.Y);
if (lvhti.Item != null)
{
contextMenuAllowed = true;
}
}
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
contextMenuAllowed = false;
}
base.OnMouseUp(e);
}
private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!contextMenuAllowed)
e.Cancel = true;
}
}
有一种非常简单的方法:
-
将上下文菜单分配给ListView对象的ContextMenuStrip属性(这可以在GUI设置中完成)
-
处理上下文菜单对象的Opening事件,并在事件处理程序中检查是否选择了ListView对象的任何项。如果不是这种情况,则取消事件:
If myListView.SelectedItems.Count = 0 Then e.Cancel = True