[英]creating a List of Custom Controls at run-time using the context menu strip Item Click Event
我正在一个自定义控件上,我想添加使用右键单击上下文菜单项click事件的实例。
我目前遇到的唯一麻烦是在这里在窗体上设置控件的位置。
public partial class frmMain : Form
{
List<GenericNode> nodeTree;
GenericNode node;
public frmMain()
{
InitializeComponent();
}
private void testItemToolStripMenuItem_Click(object sender, EventArgs e)
{
//place node item in a list with ID so that I can add many unique items
node = new GenericNode();
nodeTree = new List<GenericNode>();
nodeTree.Add(node);
node.Name = "node" + nodeTree.Count;
//set the Location of Control based on Mouse Position
如果我尝试设置node.Location.X或Y的值,它会告诉我不能为它分配值,因为它是返回值。
//add item from list to form
this.Controls.Add(nodeTree.ElementAt(nodeTree.Count -1));
}
}
好的,我回到这个问题了,没有人看到任何答案,所以我想出了一个快速的肮脏的方法,以防万一你挠头。
public partial class frmMain : Form
{
List<GenericNode> nodeTree;
GenericNode node;
Point location;
public frmMain()
{
InitializeComponent();
}
private void testItemToolStripMenuItem_Click(object sender, EventArgs e)
{
//place node item in a list with ID so that I can add many unique items
node = new GenericNode();
nodeTree = new List<GenericNode>();
nodeTree.Add(node);
node.Name = "node" + nodeTree.Count;
//place the current object on the form at given location
location = new Point(MousePosition.X, MousePosition.Y);
node.Location = location;
this.Controls.Add(nodeTree.ElementAt(nodeTree.Count - 1));
}
}
虽然我仍然无法使其与鼠标对齐,但是我尝试了偏移量,但是偏移量始终很小。
您正在使用的MousePosition将位于屏幕坐标中,因此您需要将它们转换为表单的坐标:
node.Location = PointToClient(MousePosition);
请注意,在触发菜单单击事件时将看到的MousePosition将是单击菜单项时鼠标的位置,而不是右键单击以打开上下文菜单时的位置。
其他一些评论:
不要在click事件中创建新的nodeTree-它将删除前一棵树,并且计数永远不会超过1。在构造函数中或定义类成员的行中创建它。
不要为“节点”或“位置”创建类成员变量,它们仅在click事件处理程序中使用,应在此处定义。
在最后一行中,您不需要从列表中检索节点,您已经有对其的引用。
public partial class MainForm : Form
{
private List<GenericNode> nodeTree;
public MainForm()
{
InitializeComponent();
nodeTree = new List<GenericNode>();
}
private void testitemToolStripMenuItem_Click(object sender, EventArgs e)
{
GenericNode node = new GenericNode();
nodeTree.Add(node);
node.Name = "node" + nodeTree.Count;
node.Location = PointToClient(MousePosition);
this.Controls.Add(node);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.