在Winform Design設計器內允許修改UserControl內的控件



當將UserControl添加到Winform窗體之後,在Winform窗體內,UserControl裏面的控件是不能修改的,要想修改UserControl裏面的控件,比如修改label的位置,大小等,可以試試下面的方法:

1.Create  a project and add the reference System.Design
2.Add the UserControl to your project, drap label1,splitter1 and testbox1 to the UserControl, set the Modifiers property as Public, and edit the UserControl1.cs as below:

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;
using System.Windows.Forms.Design;   // Note: add reference required

namespace UserControlPro
{
    [Designer(typeof(MyDesigner))]   // Note: custom designer
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();            
        }

        class MyDesigner : ControlDesigner //add the MyDesigner
        {
            public override void Initialize(IComponent comp)
            {
                base.Initialize(comp);
                if (this.Control is UserControl1)  // replace this with your usercontrol type
                {
                    // cast this.Control to you type of usercontrol to get at it's
                    // controls easier
                    var i = this.Control as UserControl1; // replace ***
                    this.EnableDesignMode(i.label1, "label1");
                    this.EnableDesignMode(i.textBox1, "textBox1");
                }
            }
        }
    }
}

3.Rebuild your project, drap your UserControl1 to your winform, and then you could edit your controls in the UserControl.
參考鏈接
https://support.microsoft.com/kb/813450?wa=wsignin1.0
http://stackoverflow.com/questions/14330625/c-sharp-windowsforms-usercontrols-controls-designer-support
http://stackoverflow.com/questions/2785376/how-to-enable-design-support-in-a-custom-control

發佈了41 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章