[C#學(xué)習(xí)筆記14]控件的二次開發(fā)技術(shù)
控件的二次開發(fā):以現(xiàn)有工具箱中的控件為基礎(chǔ),對其做再次封裝,添加需要定義的功能控件
給文本框添加驗證功能
????繼承——類的開發(fā)者封裝了相關(guān)功能,使用根據(jù)需要在此基礎(chǔ)上擴展相關(guān)功能(屬性、方法),A類繼承B類,A具有B的所有功能(成員)
????特性:
????????1、單根性——一個類只能繼承一個父類,不能多重繼承
????????2、傳遞性——A-〉B? ? B-〉C? ?A同時具有B和C的功能
????普通繼承——隨時可以使用,避免相同代碼重復(fù)
????繼承多態(tài)——實現(xiàn)系統(tǒng)擴展性
新建類創(chuàng)建控件,新建組件類,添加errorProvider錯誤提示
//引入窗體的命名空間
using System.Windows.Forms;
using System.Text.RegularExpressions;//這則表達式使用的命名空間
namespace MyUIControl
{
? ? public partial class SuperTextBox : TextBox//自動生成的代碼中Component->TextBox
? ? {
? ? ? ? public SuperTextBox()
? ? ? ? {
? ? ? ? ? ? InitializeComponent();
? ? ? ? }
? ? ? ? public SuperTextBox(IContainer container)
? ? ? ? {
? ? ? ? ? ? container.Add(this);
? ? ? ? ? ? InitializeComponent();
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// 非空驗證
? ? ? ? /// </summary>
? ? ? ? /// <returns></returns>
? ? ? ? public int BeginCheckEmpty()
? ? ? ? {
? ? ? ? ? ? if (this.Text.Trim() == "")
? ? ? ? ? ? {
? ? ? ? ? ? ? ? this.errorProvider.SetError(this, "必填項不能為空!");
? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? this.errorProvider.SetError(this, string.Empty);
? ? ? ? ? ? ? ? return 1;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// 使用正則表達式驗證復(fù)雜數(shù)據(jù)
? ? ? ? /// </summary>
? ? ? ? /// <param name="regularExpress"></param>
? ? ? ? /// <param name="errorMsg"></param>
? ? ? ? /// <returns></returns>
? ? ? ? public int BeginCheckData(string regularExpress, string errorMsg)
? ? ? ? {
? ? ? ? ? ? if (BeginCheckEmpty() == 0) return 0;//如果為空,則直接返回
? ? ? ? ? ? //正則表達式驗證(忽略大小寫)
? ? ? ? ? ? Regex objRegex = new Regex(regularExpress, RegexOptions.IgnoreCase);
? ? ? ? ? ? if (!objRegex.IsMatch(this.Text.Trim()))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? this.errorProvider.SetError(this, errorMsg);
? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? this.errorProvider.SetError(this, string.Empty);//清除小圓點的錯誤提示
? ? ? ? ? ? ? ? return 1;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? //根據(jù)需要把常用的正則表達式驗證封裝到這里...
? ? }
}
窗口類顯示
????????????int a = this.txtName.BeginCheckEmpty();
? ? ? ? ? ? int b = this.txtAge.BeginCheckpty();
? ? ? ? ? ? int c = this.txtAge.BeginCheckData(@"^[1-9]\d*$", "年齡必須是正整數(shù)!");
? ? ? ? ? ? int result = a * b * c;
? ? ? ? ? ? if (result != 0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //封裝對象,提交到數(shù)據(jù)庫...
? ? ? ? ? ? ? ? MessageBox.Show("提交成功!", "信息提示");
? ? ? ? ? ? }
二次開發(fā)控件的引用
????將生成控件的.dll類庫文件添加到工具箱中:工具箱空白處右鍵添加選項卡,選擇工具箱項添加自己的控件庫文件
控件:微軟提供可視化方式操作的對象
自定義用戶控件:用開發(fā)工具里面現(xiàn)有控件做二次開發(fā)
添加類庫做用戶控件——添加用戶控件(進度條)——一個label去掉文本添加背景色綠色,一個復(fù)制label背景色為白色覆蓋綠色的label,一個label顯示百分比——添加屬性高度、寬度、進度值可讀寫并加以約束