使用上下文菜单条创建运行时自定义控件列表项单击事件

时间:2014-01-30 22:29:59

标签: c# runtime custom-controls contextmenu

我正在开发一个自定义控件,我想使用右键单击上下文菜单项单击事件添加实例。

我遇到的唯一麻烦就是在此处设置控件的位置是我到目前为止所做的。

    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));
    }
}

我仍然无法让它与我的鼠标对齐,我已经尝试了偏移量,但它一直都是关闭的。

1 个答案:

答案 0 :(得分:1)

您正在使用的MousePosition将位于屏幕坐标中,因此您需要将它们转换为Form的坐标:

node.Location = PointToClient(MousePosition);

请注意,菜单点击事件触发时您将看到的MousePosition将是您单击菜单项时鼠标的位置,而不是右键单击打开上下文菜单时的位置。

其他几条评论:

不要在click事件中创建一个新的nodeTree - 这将删除前一个树,并且计数永远不会超过1.在构造函数或定义类成员的行中创建它。

不要为“node”或“location”创建类成员变量,它们仅在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);
    }
}