当前位置:首页 > Windows程序 > 正文

C#继承基本控件实现自定义控件

2021-03-28 Windows程序

标签:

C#继承基本控件实现自定义控件

摘自:

自定义控件分三类:
1.复合控件:基本控件组合而成。继承自UserControl
2.扩展控件:继承基本控件,扩展一些属性与事件。比如继承Button
3.自定义控件:直接继承自Control
第一种情况上手比较容易,也比较常用,其中也有不少技巧,慢慢总结。
比如要单独建个类库项目,,才不会引起冲突。
怎样把事件代码推迟到使用者。
今天把扩展控件简单入门。
------------------------------------------------------------------
步骤一:这里首先要建一个Windows控件库项目。
步骤二:新建用户控件,修改代码(注意注释掉.Designer.cs文件中的代码)
扩展Button

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinFormControlLibrary
{
    public partial class UcButton : Button
    {
        public UcButton()
        {
            InitializeComponent();
        }
        // Creates the private variable that will store the value of your 
        // property.
        private int varValue;
        // Declares the property.
        public int ButtonValue
        {
            // Sets the method for retrieving the value of your property.
            get
            {
                return varValue;
            }
            // Sets the method for setting the value of your property.
            set
            {
                varValue = value;
            }
        }
    }
}

修改.Desinger.cs

namespace WinFormControlLibrary
{
    partial class UcButton
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            //把这句注释掉
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        }

        #endregion
    }
}

扩展Label

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68875.html