C#中改变ContextMenuStrip中ToolStripMenuItem的顺序

来源:互联网 发布:SQL中怎么定义联合主键 编辑:程序博客网 时间:2024/05/22 13:38

      C#的ContextMenuStrip控件中,没有为ToolStripMenuItem安排顺序的属性。想要为ToolStripMenuItem排序,或者加入新项加到某个位置,无法通过属性值来控制顺序。

      但是C#不会忽略这个问题,不然人家是怎么排序的呢?

      可以看一下窗体的设计代码:

            // 
            // IconMenuStrip1
            // 
            this.IconMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.设置ToolStripMenuItem,
            this.退出ToolStripMenuItem});

            this.IconMenuStrip1.Name = "contextMenuStrip1";
            this.IconMenuStrip1.Size = new System.Drawing.Size(101, 48);
            this.IconMenuStrip1.Text = "设置";
            // 
            // 设置ToolStripMenuItem
            // 
            this.设置ToolStripMenuItem.Name = "设置ToolStripMenuItem";
            this.设置ToolStripMenuItem.Size = new System.Drawing.Size(100, 22);
            this.设置ToolStripMenuItem.Text = "设置";
            this.设置ToolStripMenuItem.Click += new System.EventHandler(this.设置ToolStripMenuItem_Click);
            // 
            // 退出ToolStripMenuItem
            // 
            this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
            this.退出ToolStripMenuItem.Size = new System.Drawing.Size(100, 22);
            this.退出ToolStripMenuItem.Text = "退出";
            this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);

          可以看到,红色字的部分,就是使用数组方式将ToolStripMenuItem放入的,这就是它的顺序。很明显,我们不知道怎么改变它的顺序,但是它用了数组的方式,可以去查一下数组是怎么改变顺序的。


    ListViewItem lvi=listView1.Items[1];  //  取得被移动项
    listView1.Items[1].Remove();      // 从listView移除被移动项
    listView1.Items.Insert(0, lvi);    // 原项移到新位置

    这是ListView的项的排序方式。

               那么,可以借用一下它的Insert方法,那它有没有呢?

              IconMenuStrip1.Items.Insert(0, NewToolStripMenuItem);


             试了一下,果然有,再看效果,果然出来了!



0 0