自訂控制項分三類:
1.複合控制項:基本控制群組合而成。繼承自UserControl
2.擴充控制項:繼承基本控制項,擴充一些屬性與事件。比如繼承Button
3.自訂控制項:直接繼承自Control
第一種情況上手比較容易,也比較常用,其中也有不少技巧,慢慢總結。
比如要單獨建個類庫項目,才不會引起衝突。
怎樣把事件代碼延遲到使用者。
今天把擴充控制項簡單入門。
------------------------------------------------------------------
步驟一:這裡首先要建一個Windows控制項陳列庫項目。
步驟二:建立使用者控制項,修改代碼(注意注釋掉.Designer.cs檔案中的代碼)
擴充Buttonusing 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.csnamespace 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
}
}
擴充Labelusing 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 UcLabel : Label
{
public UcLabel()
{
InitializeComponent();
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
this.Font = new Font("宋體", 10F, FontStyle.Underline);
}
protected override void OnMouseLeave(System.EventArgs e)
{
base.OnMouseLeave(e);
this.Font = new Font("宋體", 10F, FontStyle.Regular);
}
}
}
步驟三:在其他Windows表單項目中添加項目引用。編譯之後就在工具箱看到產生的自訂控制項。
url:http://greatverve.cnblogs.com/archive/2012/02/16/user-control-Inherit.html
參考msdn:http://msdn.microsoft.com/zh-cn/library/5h0k2e6x(v=vs.80).aspxhttp://blog.csdn.net/yysyangyangyangshan/article/details/7078471