官網
http://www.hzhcontrols.com
前提
入行已經7,8年了,一直想做一套漂亮點的自定義控制元件,于是就有了本系列文章,
GitHub:https://github.com/kwwwvagaa/NetWinformControl
碼云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
如果覺得寫的還行,請點個 star 支持一下吧
歡迎前來交流探討: 企鵝群568015492 
來都來了,點個【推薦】再走吧,謝謝
NuGet
Install-Package HZH_Controls
目錄
https://www.cnblogs.com/bfyx/p/11364884.html
用處及效果

準備作業
思路如下:
1、確定哪些控制元件需要進行驗證,在組件中進行屬性擴展
2、定義驗證規則
3、根據驗證規則的正則運算式進行驗證和非空驗證
4、觸發驗證結果事件
5、進行驗證結果提示
開始
添加一個驗證規則列舉
1 /// <summary> 2 /// 驗證規則 3 /// </summary> 4 public enum VerificationModel 5 { 6 /// <summary> 7 /// 無 8 /// </summary> 9 [Description("無"), VerificationAttribute()]10 None = 1,11 /// <summary>12 /// 任意字母數字下劃線13 /// </summary>14 [Description("任意字母數字下劃線"), VerificationAttribute(@"^[a-zA-Z_0-1]*$", "請輸入任意字母數字下劃線")]15 AnyChar = 2,16 /// <summary>17 /// 任意數字18 /// </summary>19 [Description("任意數字"), VerificationAttribute(@"^[\-\+]?\d+(\.\d+)?$", "請輸入任意數字")]20 Number = 4,21 /// <summary>22 /// 非負數23 /// </summary>24 [Description("非負數"), VerificationAttribute(@"^(\+)?\d+(\.\d+)?$", "請輸入非負數")]25 UnsignNumber = 8,26 /// <summary>27 /// 正數28 /// </summary>29 [Description("正數"), VerificationAttribute(@"(\+)?([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})", "請輸入正數")]30 PositiveNumber = 16,31 /// <summary>32 /// 整數33 /// </summary>34 [Description("整數"), VerificationAttribute(@"^[\+\-]?\d+$", "請輸入整數")]35 Integer = 32,36 /// <summary>37 /// 非負整數38 /// </summary>39 [Description("非負整數"), VerificationAttribute(@"^(\+)?\d+$", "請輸入非負整數")]40 UnsignIntegerNumber = 64,41 /// <summary>42 /// 正整數43 /// </summary>44 [Description("正整數"), VerificationAttribute(@"^[0-9]*[1-9][0-9]*$", "請輸入正整數")]45 PositiveIntegerNumber = 128,46 /// <summary>47 /// 郵箱48 /// </summary>49 [Description("郵箱"), VerificationAttribute(@"^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT)$", "請輸入正確的郵箱地址")]50 Email = 256,51 /// <summary>52 /// 手機53 /// </summary>54 [Description("手機"), VerificationAttribute(@"^(\+?86)?1\d{10}$", "請輸入正確的手機號")]55 Phone = 512,56 /// <summary>57 /// IP58 /// </summary>59 [Description("IP"), VerificationAttribute(@"(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))", "請輸入正確的IP地址")]60 IP = 1024,61 /// <summary>62 /// Url63 /// </summary>64 [Description("Url"), VerificationAttribute(@"^[a-zA-z]+://(//w+(-//w+)*)(//.(//w+(-//w+)*))*(//?//S*)?$", "請輸入正確的網址")]65 URL = 2048,66 /// <summary>67 /// 身份證號68 /// </summary>69 [Description("身份證號"), VerificationAttribute(@"^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$", "請輸入正確的身份證號")]70 IDCardNo = 4096,71 /// <summary>72 /// 正則驗證73 /// </summary>74 [Description("自定義正則運算式"), VerificationAttribute()]75 Custom = 8192,76 }
還有一個驗證規則列舉的特性
1 public class VerificationAttribute : Attribute 2 { 3 /// <summary> 4 /// Initializes a new instance of the <see cref="VerificationAttribute"/> class. 5 /// </summary> 6 /// <param name="strRegex">The string regex.</param> 7 /// <param name="strErrorMsg">The string error MSG.</param> 8 public VerificationAttribute(string strRegex = "", string strErrorMsg = "") 9 {10 Regex = strRegex;11 ErrorMsg = strErrorMsg;12 }13 /// <summary>14 /// Gets or sets the regex.15 /// </summary>16 /// <value>The regex.</value>17 public string Regex { get; set; }18 /// <summary>19 /// Gets or sets the error MSG.20 /// </summary>21 /// <value>The error MSG.</value>22 public string ErrorMsg { get; set; }23 24 }
定義事件引數
1 public class VerificationEventArgs : EventArgs 2 { 3 /// <summary> 4 /// Gets or sets the verification control. 5 /// </summary> 6 /// <value>The verification control.</value> 7 public Control VerificationControl { get; set; } 8 /// <summary> 9 /// Gets or sets a value indicating whether [verify success].10 /// </summary>11 /// <value><c>true</c> if [verify success]; otherwise, <c>false</c>.</value>12 public bool IsVerifySuccess { get; set; }13 /// <summary>14 /// Gets or sets the verification model.15 /// </summary>16 /// <value>The verification model.</value>17 public VerificationModel VerificationModel { get; set; }18 /// <summary>19 /// 是否已處理,如果為true,則不再使用默認驗證提示功能20 /// </summary>21 /// <value><c>true</c> if this instance is processed; otherwise, <c>false</c>.</value>22 public bool IsProcessed { get; set; }23 /// <summary>24 /// Gets or sets 正則運算式25 /// </summary>26 /// <value>The custom regex.</value>27 public string Regex { get; set; }28 /// <summary>29 /// Gets or sets a value indicating whether this <see cref="VerificationEventArgs"/> is required.30 /// </summary>31 /// <value><c>true</c> if required; otherwise, <c>false</c>.</value>32 public bool Required { get; set; }33 34 /// <summary>35 /// Gets or sets the error MSG.36 /// </summary>37 /// <value>The error MSG.</value>38 public string ErrorMsg { get; set; }39 }
添加一個類VerificationComponent繼承Component,實作介面 IExtenderProvider以對控制元件進行擴展
定義屬性
1 /// <summary> 2 /// Delegate VerificationedHandle 3 /// </summary> 4 /// <param name="e">The <see cref="VerificationEventArgs"/> instance containing the event data.</param> 5 public delegate void VerificationedHandle(VerificationEventArgs e); 6 /// <summary> 7 /// Occurs when [verificationed]. 8 /// </summary> 9 [Browsable(true), Category("自定義屬性"), Description("驗證事件"), Localizable(true)]10 public event VerificationedHandle Verificationed;11 12 /// <summary>13 /// The m control cache14 /// </summary>15 Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();16 /// <summary>17 /// The m control regex cache18 /// </summary>19 Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();20 /// <summary>21 /// The m control required cache22 /// </summary>23 Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();24 /// <summary>25 /// The m control MSG cache26 /// </summary>27 Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>();28 /// <summary>29 /// The m control tips30 /// </summary>31 Dictionary<Control, Forms.FrmAnchorTips> m_controlTips = new Dictionary<Control, Forms.FrmAnchorTips>();32 33 /// <summary>34 /// The error tips back color35 /// </summary>36 private Color errorTipsBackColor = Color.FromArgb(255, 77, 58);37 38 /// <summary>39 /// Gets or sets the color of the error tips back.40 /// </summary>41 /// <value>The color of the error tips back.</value>42 [Browsable(true), Category("自定義屬性"), Description("錯誤提示背景色"), Localizable(true)]43 public Color ErrorTipsBackColor44 {45 get { return errorTipsBackColor; }46 set { errorTipsBackColor = value; }47 }48 49 /// <summary>50 /// The error tips fore color51 /// </summary>52 private Color errorTipsForeColor = Color.White;53 54 /// <summary>55 /// Gets or sets the color of the error tips fore.56 /// </summary>57 /// <value>The color of the error tips fore.</value>58 [Browsable(true), Category("自定義屬性"), Description("錯誤提示文字顏色"), Localizable(true)]59 public Color ErrorTipsForeColor60 {61 get { return errorTipsForeColor; }62 set { errorTipsForeColor = value; }63 }
哪些控制元件需要進行驗證(屬性擴展)
1 public bool CanExtend(object extendee)2 {3 if (extendee is TextBoxBase || extendee is UCTextBoxEx || extendee is ComboBox || extendee is UCCombox)4 {5 return true;6 }7 return false;8 }
擴展屬性
1 /// <summary> 2 /// The m control cache 3 /// </summary> 4 Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>(); 5 /// <summary> 6 /// The m control regex cache 7 /// </summary> 8 Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>(); 9 /// <summary> 10 /// The m control required cache 11 /// </summary> 12 Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>(); 13 /// <summary> 14 /// The m control MSG cache 15 /// </summary> 16 Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>(); 17 18 #region 驗證規則 English:Validation rule 19 /// <summary> 20 /// Gets the verification model. 21 /// </summary> 22 /// <param name="control">The control.</param> 23 /// <returns>VerificationModel.</returns> 24 [Browsable(true), Category("自定義屬性"), Description("驗證規則"), DisplayName("VerificationModel"), Localizable(true)] 25 public VerificationModel GetVerificationModel(Control control) 26 { 27 if (m_controlCache.ContainsKey(control)) 28 { 29 return m_controlCache[control]; 30 } 31 else 32 return VerificationModel.None; 33 } 34 35 /// <summary> 36 /// Sets the verification model. 37 /// </summary> 38 /// <param name="control">The control.</param> 39 /// <param name="vm">The vm.</param> 40 public void SetVerificationModel(Control control, VerificationModel vm) 41 { 42 m_controlCache[control] = vm; 43 } 44 #endregion 45 46 #region 自定義正則 English:Custom Rules 47 /// <summary> 48 /// Gets the verification custom regex. 49 /// </summary> 50 /// <param name="control">The control.</param> 51 /// <returns>System.String.</returns> 52 [Browsable(true), Category("自定義屬性"), Description("自定義驗證正則運算式"), DisplayName("VerificationCustomRegex"), Localizable(true)] 53 public string GetVerificationCustomRegex(Control control) 54 { 55 if (m_controlRegexCache.ContainsKey(control)) 56 { 57 return m_controlRegexCache[control]; 58 } 59 else 60 return ""; 61 } 62 63 /// <summary> 64 /// Sets the verification custom regex. 65 /// </summary> 66 /// <param name="control">The control.</param> 67 /// <param name="strRegex">The string regex.</param> 68 public void SetVerificationCustomRegex(Control control, string strRegex) 69 { 70 m_controlRegexCache[control] = strRegex; 71 } 72 #endregion 73 74 #region 必填 English:Must fill 75 /// <summary> 76 /// Gets the verification required. 77 /// </summary> 78 /// <param name="control">The control.</param> 79 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> 80 [Browsable(true), Category("自定義屬性"), Description("是否必填項"), DisplayName("VerificationRequired"), Localizable(true)] 81 public bool GetVerificationRequired(Control control) 82 { 83 if (m_controlRequiredCache.ContainsKey(control)) 84 return m_controlRequiredCache[control]; 85 return false; 86 } 87 88 /// <summary> 89 /// Sets the verification required. 90 /// </summary> 91 /// <param name="control">The control.</param> 92 /// <param name="blnRequired">if set to <c>true</c> [BLN required].</param> 93 public void SetVerificationRequired(Control control, bool blnRequired) 94 { 95 m_controlRequiredCache[control] = blnRequired; 96 } 97 #endregion 98 99 #region 提示資訊 English:Prompt information100 /// <summary>101 /// Gets the verification error MSG.102 /// </summary>103 /// <param name="control">The control.</param>104 /// <returns>System.String.</returns>105 [Browsable(true), Category("自定義屬性"), Description("驗證錯誤提示資訊,當為空時則使用默認提示資訊"), DisplayName("VerificationErrorMsg"), Localizable(true)]106 public string GetVerificationErrorMsg(Control control)107 {108 if (m_controlMsgCache.ContainsKey(control))109 return m_controlMsgCache[control];110 return "";111 }112 113 /// <summary>114 /// Sets the verification error MSG.115 /// </summary>116 /// <param name="control">The control.</param>117 /// <param name="strErrorMsg">The string error MSG.</param>118 public void SetVerificationErrorMsg(Control control, string strErrorMsg)119 {120 m_controlMsgCache[control] = strErrorMsg;121 }122 #endregion
驗證處理
1 #region 驗證 English:Verification 2 /// <summary> 3 /// 功能描述:驗證 English:Verification result processing 4 /// 作 者:HZH 5 /// 創建日期:2019-09-28 09:02:49 6 /// 任務編號:POS 7 /// </summary> 8 /// <param name="c">c</param> 9 /// <returns>回傳值</returns> 10 public bool Verification(Control c) 11 { 12 bool bln = true; 13 if (m_controlCache.ContainsKey(c)) 14 { 15 var vm = m_controlCache[c]; 16 string strRegex = ""; 17 string strErrMsg = ""; 18 #region 獲取正則或默認錯誤提示 English:Get regular or error prompts 19 if (vm == VerificationModel.Custom) 20 { 21 //自定義正則 22 if (m_controlRegexCache.ContainsKey(c)) 23 { 24 strRegex = m_controlRegexCache[c]; 25 strErrMsg = "不正確的輸入"; 26 } 27 } 28 else 29 { 30 //獲取默認正則和錯誤提示 31 Type type = vm.GetType(); //獲取型別 32 MemberInfo[] memberInfos = type.GetMember(vm.ToString()); 33 if (memberInfos.Length > 0) 34 { 35 var atts = memberInfos[0].GetCustomAttributes(typeof(VerificationAttribute), false); 36 if (atts.Length > 0) 37 { 38 var va = ((VerificationAttribute)atts[0]); 39 strErrMsg = va.ErrorMsg; 40 strRegex = va.Regex; 41 } 42 } 43 } 44 #endregion 45 46 #region 取值 English:Value 47 string strValue = https://www.cnblogs.com/bfyx/p/""; 48 if (c is TextBoxBase) 49 { 50 strValue = https://www.cnblogs.com/bfyx/p/(c as TextBoxBase).Text; 51 } 52 else if (c is UCTextBoxEx) 53 { 54 strValue = https://www.cnblogs.com/bfyx/p/(c as UCTextBoxEx).InputText; 55 } 56 else if (c is ComboBox) 57 { 58 var cbo = (c as ComboBox); 59 if (cbo.DropDownStyle == ComboBoxStyle.DropDownList) 60 { 61 strValue = https://www.cnblogs.com/bfyx/p/cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString(); 62 } 63 else 64 { 65 strValue =https://www.cnblogs.com/bfyx/p/ cbo.Text; 66 } 67 } 68 else if (c is UCCombox) 69 { 70 strValue = https://www.cnblogs.com/bfyx/p/(c as UCCombox).SelectedText; 71 } 72 #endregion 73 74 //自定義錯誤資訊 75 if (m_controlMsgCache.ContainsKey(c) && !string.IsNullOrEmpty(m_controlMsgCache[c])) 76 strErrMsg = m_controlMsgCache[c]; 77 78 //檢查必填項 79 if (m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c]) 80 { 81 if (string.IsNullOrEmpty(strValue)) 82 { 83 VerControl(new VerificationEventArgs() 84 { 85 VerificationModel = vm, 86 Regex = strRegex, 87 ErrorMsg = "不能為空", 88 IsVerifySuccess = false, 89 Required = true, 90 VerificationControl = c 91 }); 92 bln = false; 93 return false; 94 } 95 } 96 //驗證正則 97 if (!string.IsNullOrEmpty(strValue)) 98 { 99 if (!string.IsNullOrEmpty(strRegex))100 {101 if (!Regex.IsMatch(strValue, strRegex))102 {103 VerControl(new VerificationEventArgs()104 {105 VerificationModel = vm,106 Regex = strRegex,107 ErrorMsg = strErrMsg,108 IsVerifySuccess = false,109 Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],110 VerificationControl = c111 });112 bln = false;113 return false;114 }115 }116 }117 //沒有問題出發一個成功資訊118 VerControl(new VerificationEventArgs()119 {120 VerificationModel = vm,121 Regex = strRegex,122 ErrorMsg = strErrMsg,123 IsVerifySuccess = true,124 Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],125 VerificationControl = c126 });127 }128 return bln;129 }130 #endregion131 #region 驗證 English:Verification132 /// <summary>133 /// 功能描述:驗證 English:Verification134 /// 作 者:HZH135 /// 創建日期:2019-09-27 17:54:38136 /// 任務編號:POS137 /// </summary>138 /// <returns>回傳值</returns>139 public bool Verification()140 {141 bool bln = true;142 foreach (var item in m_controlCache)143 {144 Control c = item.Key;145 if (!Verification(c))146 {147 bln = false;148 }149 }150 return bln;151 }152 #endregion153 154 155 156 #region 驗證結果處理 English:Verification result processing157 /// <summary>158 /// 功能描述:驗證結果處理 English:Verification result processing159 /// 作 者:HZH160 /// 創建日期:2019-09-27 17:54:59161 /// 任務編號:POS162 /// </summary>163 /// <param name="e">e</param>164 private void VerControl(VerificationEventArgs e)165 {166 //如果成功則移除失敗提示167 if (e.IsVerifySuccess)168 {169 if (m_controlTips.ContainsKey(e.VerificationControl))170 {171 m_controlTips[e.VerificationControl].Close();172 m_controlTips.Remove(e.VerificationControl);173 }174 }175 //觸發事件176 if (Verificationed != null)177 {178 Verificationed(e);179 if (e.IsProcessed)//如果已處理,則不再向下執行180 {181 return;182 }183 }184 //如果失敗則顯示提示185 if (!e.IsVerifySuccess)186 {187 if (m_controlTips.ContainsKey(e.VerificationControl))188 {189 m_controlTips[e.VerificationControl].StrMsg = e.ErrorMsg;190 }191 else192 {193 var tips = Forms.FrmAnchorTips.ShowTips(e.VerificationControl, e.ErrorMsg, background: errorTipsBackColor, foreColor: errorTipsForeColor, autoCloseTime: 0, blnTopMost: false);194 m_controlTips[e.VerificationControl] = tips;195 }196 }197 }198 #endregion
完整代碼

1 // *********************************************************************** 2 // Assembly : HZH_Controls 3 // Created : 2019-09-27 4 // 5 // *********************************************************************** 6 // <copyright file="VerificationComponent.cs"> 7 // Copyright by Huang Zhenghui(黃正輝) All, QQ group:568015492 QQ:623128629 Email:[email protected] 8 // </copyright> 9 // 10 // Blog: https://www.cnblogs.com/bfyx 11 // GitHub:https://github.com/kwwwvagaa/NetWinformControl 12 // gitee:https://gitee.com/kwwwvagaa/net_winform_custom_control.git 13 // 14 // If you use this code, please keep this note. 15 // *********************************************************************** 16 using System; 17 using System.Collections.Generic; 18 using System.ComponentModel; 19 using System.Drawing; 20 using System.Linq; 21 using System.Reflection; 22 using System.Text; 23 using System.Text.RegularExpressions; 24 using System.Windows.Forms; 25 26 namespace HZH_Controls.Controls 27 { 28 /// <summary> 29 /// Class VerificationComponent. 30 /// Implements the <see cref="System.ComponentModel.Component" /> 31 /// Implements the <see cref="System.ComponentModel.IExtenderProvider" /> 32 /// </summary> 33 /// <seealso cref="System.ComponentModel.Component" /> 34 /// <seealso cref="System.ComponentModel.IExtenderProvider" /> 35 [ProvideProperty("VerificationModel", typeof(Control))] 36 [ProvideProperty("VerificationCustomRegex", typeof(Control))] 37 [ProvideProperty("VerificationRequired", typeof(Control))] 38 [ProvideProperty("VerificationErrorMsg", typeof(Control))] 39 [DefaultEvent("Verificationed")] 40 public class VerificationComponent : Component, IExtenderProvider 41 { 42 /// <summary> 43 /// Delegate VerificationedHandle 44 /// </summary> 45 /// <param name="e">The <see cref="VerificationEventArgs"/> instance containing the event data.</param> 46 public delegate void VerificationedHandle(VerificationEventArgs e); 47 /// <summary> 48 /// Occurs when [verificationed]. 49 /// </summary> 50 [Browsable(true), Category("自定義屬性"), Description("驗證事件"), Localizable(true)] 51 public event VerificationedHandle Verificationed; 52 53 /// <summary> 54 /// The m control cache 55 /// </summary> 56 Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>(); 57 /// <summary> 58 /// The m control regex cache 59 /// </summary> 60 Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>(); 61 /// <summary> 62 /// The m control required cache 63 /// </summary> 64 Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>(); 65 /// <summary> 66 /// The m control MSG cache 67 /// </summary> 68 Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>(); 69 /// <summary> 70 /// The m control tips 71 /// </summary> 72 Dictionary<Control, Forms.FrmAnchorTips> m_controlTips = new Dictionary<Control, Forms.FrmAnchorTips>(); 73 74 /// <summary> 75 /// The error tips back color 76 /// </summary> 77 private Color errorTipsBackColor = Color.FromArgb(255, 77, 58); 78 79 /// <summary> 80 /// Gets or sets the color of the error tips back. 81 /// </summary> 82 /// <value>The color of the error tips back.</value> 83 [Browsable(true), Category("自定義屬性"), Description("錯誤提示背景色"), Localizable(true)] 84 public Color ErrorTipsBackColor 85 { 86 get { return errorTipsBackColor; } 87 set { errorTipsBackColor = value; } 88 } 89 90 /// <summary> 91 /// The error tips fore color 92 /// </summary> 93 private Color errorTipsForeColor = Color.White; 94 95 /// <summary> 96 /// Gets or sets the color of the error tips fore. 97 /// </summary> 98 /// <value>The color of the error tips fore.</value> 99 [Browsable(true), Category("自定義屬性"), Description("錯誤提示文字顏色"), Localizable(true)]100 public Color ErrorTipsForeColor101 {102 get { return errorTipsForeColor; }103 set { errorTipsForeColor = value; }104 }105 106 #region 建構式 English:Constructor107 /// <summary>108 /// Initializes a new instance of the <see cref="VerificationComponent"/> class.109 /// </summary>110 public VerificationComponent()111 {112 113 }114 115 /// <summary>116 /// Initializes a new instance of the <see cref="VerificationComponent"/> class.117 /// </summary>118 /// <param name="container">The container.</param>119 public VerificationComponent(IContainer container)120 : this()121 {122 container.Add(this);123 }124 #endregion125 126 #region 指定此物件是否可以將其擴展程式屬性提供給指定的物件, English:Specifies whether this object can provide its extender properties to the specified object.127 /// <summary>128 /// 指定此物件是否可以將其擴展程式屬性提供給指定的物件,129 /// </summary>130 /// <param name="extendee">要接收擴展程式屬性的 <see cref="T:System.Object" />,</param>131 /// <returns>如果此物件可以擴展程式屬性提供給指定物件,則為 true;否則為 false,</returns>132 public bool CanExtend(object extendee)133 {134 if (extendee is TextBoxBase || extendee is UCTextBoxEx || extendee is ComboBox || extendee is UCCombox)135 {136 return true;137 }138 return false;139 }140 #endregion141 142 #region 驗證規則 English:Validation rule143 /// <summary>144 /// Gets the verification model.145 /// </summary>146 /// <param name="control">The control.</param>147 /// <returns>VerificationModel.</returns>148 [Browsable(true), Category("自定義屬性"), Description("驗證規則"), DisplayName("VerificationModel"), Localizable(true)]149 public VerificationModel GetVerificationModel(Control control)150 {151 if (m_controlCache.ContainsKey(control))152 {153 return m_controlCache[control];154 }155 else156 return VerificationModel.None;157 }158 159 /// <summary>160 /// Sets the verification model.161 /// </summary>162 /// <param name="control">The control.</param>163 /// <param name="vm">The vm.</param>164 public void SetVerificationModel(Control control, VerificationModel vm)165 {166 m_controlCache[control] = vm;167 }168 #endregion169 170 #region 自定義正則 English:Custom Rules171 /// <summary>172 /// Gets the verification custom regex.173 /// </summary>174 /// <param name="control">The control.</param>175 /// <returns>System.String.</returns>176 [Browsable(true), Category("自定義屬性"), Description("自定義驗證正則運算式"), DisplayName("VerificationCustomRegex"), Localizable(true)]177 public string GetVerificationCustomRegex(Control control)178 {179 if (m_controlRegexCache.ContainsKey(control))180 {181 return m_controlRegexCache[control];182 }183 else184 return "";185 }186 187 /// <summary>188 /// Sets the verification custom regex.189 /// </summary>190 /// <param name="control">The control.</param>191 /// <param name="strRegex">The string regex.</param>192 public void SetVerificationCustomRegex(Control control, string strRegex)193 {194 m_controlRegexCache[control] = strRegex;195 }196 #endregion197 198 #region 必填 English:Must fill199 /// <summary>200 /// Gets the verification required.201 /// </summary>202 /// <param name="control">The control.</param>203 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>204 [Browsable(true), Category("自定義屬性"), Description("是否必填項"), DisplayName("VerificationRequired"), Localizable(true)]205 public bool GetVerificationRequired(Control control)206 {207 if (m_controlRequiredCache.ContainsKey(control))208 return m_controlRequiredCache[control];209 return false;210 }211 212 /// <summary>213 /// Sets the verification required.214 /// </summary>215 /// <param name="control">The control.</param>216 /// <param name="blnRequired">if set to <c>true</c> [BLN required].</param>217 public void SetVerificationRequired(Control control, bool blnRequired)218 {219 m_controlRequiredCache[control] = blnRequired;220 }221 #endregion222 223 #region 提示資訊 English:Prompt information224 /// <summary>225 /// Gets the verification error MSG.226 /// </summary>227 /// <param name="control">The control.</param>228 /// <returns>System.String.</returns>229 [Browsable(true), Category("自定義屬性"), Description("驗證錯誤提示資訊,當為空時則使用默認提示資訊"), DisplayName("VerificationErrorMsg"), Localizable(true)]230 public string GetVerificationErrorMsg(Control control)231 {232 if (m_controlMsgCache.ContainsKey(control))233 return m_controlMsgCache[control];234 return "";235 }236 237 /// <summary>238 /// Sets the verification error MSG.239 /// </summary>240 /// <param name="control">The control.</param>241 /// <param name="strErrorMsg">The string error MSG.</param>242 public void SetVerificationErrorMsg(Control control, string strErrorMsg)243 {244 m_controlMsgCache[control] = strErrorMsg;245 }246 #endregion247 248 249 #region 驗證 English:Verification250 /// <summary>251 /// 功能描述:驗證 English:Verification result processing252 /// 作 者:HZH253 /// 創建日期:2019-09-28 09:02:49254 /// 任務編號:POS255 /// </summary>256 /// <param name="c">c</param>257 /// <returns>回傳值</returns>258 public bool Verification(Control c)259 {260 bool bln = true;261 if (m_controlCache.ContainsKey(c))262 {263 var vm = m_controlCache[c];264 string strRegex = "";265 string strErrMsg = "";266 #region 獲取正則或默認錯誤提示 English:Get regular or error prompts267 if (vm == VerificationModel.Custom)268 {269 //自定義正則270 if (m_controlRegexCache.ContainsKey(c))271 {272 strRegex = m_controlRegexCache[c];273 strErrMsg = "不正確的輸入";274 }275 }276 else277 {278 //獲取默認正則和錯誤提示279 Type type = vm.GetType(); //獲取型別 280 MemberInfo[] memberInfos = type.GetMember(vm.ToString());281 if (memberInfos.Length > 0)282 {283 var atts = memberInfos[0].GetCustomAttributes(typeof(VerificationAttribute), false);284 if (atts.Length > 0)285 {286 var va = ((VerificationAttribute)atts[0]);287 strErrMsg = va.ErrorMsg;288 strRegex = va.Regex;289 }290 }291 }292 #endregion293 294 #region 取值 English:Value295 string strValue = https://www.cnblogs.com/bfyx/p/"";296 if (c is TextBoxBase)297 {298 strValue = https://www.cnblogs.com/bfyx/p/(c as TextBoxBase).Text;299 }300 else if (c is UCTextBoxEx)301 {302 strValue = https://www.cnblogs.com/bfyx/p/(c as UCTextBoxEx).InputText;303 }304 else if (c is ComboBox)305 {306 var cbo = (c as ComboBox);307 if (cbo.DropDownStyle == ComboBoxStyle.DropDownList)308 {309 strValue = https://www.cnblogs.com/bfyx/p/cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString();310 }311 else312 {313 strValue =https://www.cnblogs.com/bfyx/p/ cbo.Text;314 }315 }316 else if (c is UCCombox)317 {318 strValue = https://www.cnblogs.com/bfyx/p/(c as UCCombox).SelectedText;319 }320 #endregion321 322 //自定義錯誤資訊323 if (m_controlMsgCache.ContainsKey(c) && !string.IsNullOrEmpty(m_controlMsgCache[c]))324 strErrMsg = m_controlMsgCache[c];325 326 //檢查必填項327 if (m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c])328 {329 if (string.IsNullOrEmpty(strValue))330 {331 VerControl(new VerificationEventArgs()332 {333 VerificationModel = vm,334 Regex = strRegex,335 ErrorMsg = "不能為空",336 IsVerifySuccess = false,337 Required = true,338 VerificationControl = c339 });340 bln = false;341 return false;342 }343 }344 //驗證正則345 if (!string.IsNullOrEmpty(strValue))346 {347 if (!string.IsNullOrEmpty(strRegex))348 {349 if (!Regex.IsMatch(strValue, strRegex))350 {351 VerControl(new VerificationEventArgs()352 {353 VerificationModel = vm,354 Regex = strRegex,355 ErrorMsg = strErrMsg,356 IsVerifySuccess = false,357 Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],358 VerificationControl = c359 });360 bln = false;361 return false;362 }363 }364 }365 //沒有問題出發一個成功資訊366 VerControl(new VerificationEventArgs()367 {368 VerificationModel = vm,369 Regex = strRegex,370 ErrorMsg = strErrMsg,371 IsVerifySuccess = true,372 Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],373 VerificationControl = c374 });375 }376 return bln;377 }378 #endregion379 #region 驗證 English:Verification380 /// <summary>381 /// 功能描述:驗證 English:Verification382 /// 作 者:HZH383 /// 創建日期:2019-09-27 17:54:38384 /// 任務編號:POS385 /// </summary>386 /// <returns>回傳值</returns>387 public bool Verification()388 {389 bool bln = true;390 foreach (var item in m_controlCache)391 {392 Control c = item.Key;393 if (!Verification(c))394 {395 bln = false;396 }397 }398 return bln;399 }400 #endregion401 402 403 404 #region 驗證結果處理 English:Verification result processing405 /// <summary>406 /// 功能描述:驗證結果處理 English:Verification result processing407 /// 作 者:HZH408 /// 創建日期:2019-09-27 17:54:59409 /// 任務編號:POS410 /// </summary>411 /// <param name="e">e</param>412 private void VerControl(VerificationEventArgs e)413 {414 //如果成功則移除失敗提示415 if (e.IsVerifySuccess)416 {417 if (m_controlTips.ContainsKey(e.VerificationControl))418 {419 m_controlTips[e.VerificationControl].Close();420 m_controlTips.Remove(e.VerificationControl);421 }422 }423 //觸發事件424 if (Verificationed != null)425 {426 Verificationed(e);427 if (e.IsProcessed)//如果已處理,則不再向下執行428 {429 return;430 }431 }432 //如果失敗則顯示提示433 if (!e.IsVerifySuccess)434 {435 if (m_controlTips.ContainsKey(e.VerificationControl))436 {437 m_controlTips[e.VerificationControl].StrMsg = e.ErrorMsg;438 }439 else440 {441 var tips = Forms.FrmAnchorTips.ShowTips(e.VerificationControl, e.ErrorMsg, background: errorTipsBackColor, foreColor: errorTipsForeColor, autoCloseTime: 0, blnTopMost: false);442 m_controlTips[e.VerificationControl] = tips;443 }444 }445 }446 #endregion447 }448 }View Code
最后的話
如果你喜歡的話,請到 https://gitee.com/kwwwvagaa/net_winform_custom_control 點個星星吧
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/4898.html
標籤:WinForm

