在Winform项目中,界面美观也是需要的,经常遇到界面元素不统一的情况,比如Button有大有小,比如都是保存,但每个页
面的快捷键还不一定相同,为在项目中统一元素,我将Button进行了封装,把常用的按钮统一到一个控件中:
1、首先定义一个Button类型枚举类
1 public enum ButtonType 2 { 3 ///4 /// 保存 5 /// 6 Save = 0, 7 8 ///9 /// 退出10 /// 11 Quit = 1,12 13 ///14 /// 确定15 /// 16 Confirm = 2,17 18 ///19 /// 取消20 /// 21 Cancle = 3,22 23 ///24 /// 新建25 /// 26 New = 4,27 28 ///29 /// 编辑30 /// 31 Edit = 5,32 33 ///34 /// 删除35 /// 36 Delete = 6,37 38 ///39 /// 查询40 /// 41 Query = 7,42 43 ///44 /// 应用45 /// 46 Apply = 8,47 48 ///49 /// 添加50 /// 51 Add = 9,52 53 ///54 /// 自定义55 /// 56 Other = 9957 }
2、建一个统一Button类,集成Button控件
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.ComponentModel; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 using System.Windows.Forms; 9 10 namespace UcTool11 {12 public class UcButton : Button13 {14 15 public UcButton()16 {17 //初始化按钮类型枚举18 InitButtonDictionary();19 //初始化按钮样式20 InitButtonStyle(); 21 }22 23 private void InitButtonStyle()24 {25 base.Size = new System.Drawing.Size(93, 30);26 }27 28 #region 按钮属性29 private ButtonType _B_Type;30 ///31 /// 按钮类型32 /// 33 [Description("按钮类型")]34 public ButtonType B_Type35 {36 get37 {38 return _B_Type;39 }40 set41 {42 _B_Type = value;43 Text = ButtonDictionary[value];44 }45 }46 47 [Description("按钮文本")] 48 public new string Text49 {50 get { return base.Text; }51 set { base.Text = value; }52 }53 54 #endregion55 56 #region 一次性载入按钮字典57 private static DictionaryButtonDictionary;58 private void InitButtonDictionary()59 {60 if (ButtonDictionary == null || ButtonDictionary.Count == 0)61 {62 ButtonDictionary = new Dictionary ();63 ButtonDictionary.Add(ButtonType.Save, "保存(&S)");64 ButtonDictionary.Add(ButtonType.Quit, "退出(&U)");65 ButtonDictionary.Add(ButtonType.Confirm, "确定(&O)");66 ButtonDictionary.Add(ButtonType.Cancle, "取消(&C)");67 ButtonDictionary.Add(ButtonType.New, "新建(&N)");68 ButtonDictionary.Add(ButtonType.Edit, "编辑(&E)");69 ButtonDictionary.Add(ButtonType.Delete, "删除(&D)");70 ButtonDictionary.Add(ButtonType.Query, "查询(&Q)");71 ButtonDictionary.Add(ButtonType.Apply, "应用(&A)");72 ButtonDictionary.Add(ButtonType.Add, "添加(&M)");73 ButtonDictionary.Add(ButtonType.Other, "自定义");74 }75 }76 #endregion77 }78 }
在使用的过程中遇到常用的按钮只需要修改该Button的【B_Type】属性即可,后期也可统一对按钮的样式进行调整;