我如何使用UserControl?

时间:2017-06-30 02:57:07

标签: c# winforms generics user-controls

  1. 开发者环境

    • 工具:Visual Studio 2017
    • 语言:C# - Windows窗体
  2. 创建UserControl

    • testNext属性为Generic Type

    // ------- testControl.Designer.cs --------------------------------- -----

    partial class testTextBox<T>
    {
        private System.ComponentModel.IContainer components = null;
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // textBox1
            this.textBox1.Location = new System.Drawing.Point(3, 2);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(147, 21);
            this.textBox1.TabIndex = 1;
            this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.testTextBox_KeyPress);
            // testTextBox
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.textBox1);
            this.Margin = new System.Windows.Forms.Padding(0);
            this.Name = "testTextBox";
            this.Size = new System.Drawing.Size(157, 26);
            this.Resize += new System.EventHandler(this.testTextBox_Resize);
            this.ResumeLayout(false);
            this.PerformLayout();
        }            
        private System.Windows.Forms.TextBox textBox1;
    }
    

    // ------- testControl.cs ----------------------------------- -----------------

    public partial class testTextBox<T> : UserControl
    {
        public delegate void DelegateKeyPress(object sender, KeyPressEventArgs e);
        public event DelegateKeyPress testKeyPress;  
        public testTextBox()
        {
            InitializeComponent();
        }
        public T _testNext;  // Generic property
        public T testNext
        {
            get
            {
                return this._testNext;
            }
            set
            {
                this._testNext = value;
            }
        }
        private void testTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this._testNext != null)
            {
                MessageBox.Show(this._testNext.GetType().Name);
            }
            if (this.testKeyPress != null)
            {
                this.testKeyPress(sender, e);
            }
        }
    }
    
  3. 使用testTextBox

    • 我想在表单中使用testTextBox,但我不能在设计模式下使用它 我如何使用testTextBox?

1 个答案:

答案 0 :(得分:0)

1.确保usercontrol和mainform具有相同的命名空间。

  1. 构建解决方案

  2. 双击testControl.cs以打开设计窗口。

  3. 转到工具箱,找到** Comopnets(**是您的项目名称)

  4. 您的用户控件就在那里。只需添加和使用。