【发布时间】:2021-08-21 07:59:55
【问题描述】:
我希望能够单击列表视图控件中的选择项,而不是用鼠标右键单击并显示一些东西。
这是我创建的服装控件:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Search_Text_In_Files
{
public partial class ListViewCostumControl : UserControl
{
public static ListViewControl lvnf;
public ListViewCostumControl()
{
InitializeComponent();
lvnf = new ListViewControl();
lvnf.Location = new Point(50, 50);
lvnf.Size = new Size(50, 50);
lvnf.View = View.Details;
lvnf.Dock = DockStyle.Fill;
lvnf.SuspendLayout();
lvnf.LabelEdit = true;
lvnf.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
lvnf.Columns.Add("", 984, HorizontalAlignment.Left);
//lvnf.Columns.Add("Subject", 200);
//lvnf.Columns.Add("Date", 300);
lvnf.Sorting = SortOrder.None;
//lvnf.ColumnClick += lvnf_ColumnClick;
//lvnf.Click += lvnf_Click;
//lvnf.SelectedIndexChanged += lvnf_SelectedIndexChanged;
this.Controls.Add(lvnf);
lvnf.ResumeLayout(false);
}
public class ListViewControl : System.Windows.Forms.ListView
{
public ListViewControl()
{
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
protected override void OnNotifyMessage(System.Windows.Forms.Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}
private void ListViewNFTest_Load(object sender, EventArgs e)
{
}
}
}
比Form1:
ListViewCostumControl.lvnf.MouseClick += Lvnf_MouseClick;
在事件中:
private void Lvnf_MouseClick(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var focusedItem = ListViewCostumControl.lvnf.FocusedItem;
if (focusedItem != null && focusedItem.Bounds.Contains(e.Location))
{
contextMenuStrip1.Show(Cursor.Position);
}
}
}
但在列表视图中用鼠标右键单击所选项目时,它没有显示任何内容。
【问题讨论】:
-
你为什么有
public static ListViewControl lvnf;?所以据称您可以从外部访问它?或者这个控件(无论是什么)在你的 UserControl 的所有实例中都是相同的对象(所以 UserControl 的所有实例都将显示相同的内容)? -- ListView 有一个HitTest,可让您确定哪些 ListViewItems 或 ListViewSubItems 已被单击或选择。例如,How to get the selected SubItem index in a Listview and highlight it? -
你试过
lvnf.ContextMenuStrip = contextMenuStrip1没有Lvnf_MouseClick吗? -
使用 MouseDown !