前提
入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章。
GitHub:https://github.com/kwwwvagaa/NetWinformControl
码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
如果觉得写的还行,请点个 star 支持一下吧
目录
https://www.cnblogs.com/bfyx/p/11364884.html
准备工作
梳理一下需求,我们需要一个横向的节点列表控件,可以进行左右翻页
根据上面所写的需求,我们需要分为2步操作,1:创建项控件,2:创建列表控件
开始
首先我们创建项控件,添加一个用户控件,命名UCHorizontalListItem
代码量并不多,我们看下完整代码
1 // 版权所有 黄正辉 交流群:568015492 QQ:623128629 2 // 文件名称:UCHorizontalListItem.cs 3 // 创建日期:2019-08-15 16:01:13 4 // 功能描述:HorizontalList 5 // 项目地址:https://gitee.com/kwwwvagaa/net_winform_custom_control 6 using System; 7 using System.Collections.Generic; 8 using System.ComponentModel; 9 using System.Drawing; 10 using System.Data; 11 using System.Linq; 12 using System.Text; 13 using System.Windows.Forms; 14 15 namespace HZH_Controls.Controls 16 { 17 [ToolboxItem(false)] 18 public partial class UCHorizontalListItem : UserControl 19 { 20 public event EventHandler SelectedItem; 21 private KeyValuePair<string, string> _DataSource = new KeyValuePair<string, string>(); 22 public KeyValuePair<string, string> DataSource 23 { 24 get { return _DataSource; } 25 set 26 { 27 _DataSource = value; 28 int intWidth = ControlHelper.GetStringWidth(value.Value, lblTitle.CreateGraphics(), lblTitle.Font); 29 if (intWidth < 50) 30 intWidth = 50; 31 this.Width = intWidth + 20; 32 lblTitle.Text = value.Value; 33 SetSelect(false); 34 } 35 } 36 public UCHorizontalListItem() 37 { 38 InitializeComponent(); 39 this.Dock = DockStyle.Right; 40 this.MouseDown += Item_MouseDown; 41 this.lblTitle.MouseDown += Item_MouseDown; 42 this.ucSplitLine_H1.MouseDown += Item_MouseDown; 43 } 44 45 void Item_MouseDown(object sender, MouseEventArgs e) 46 { 47 if (SelectedItem != null) 48 SelectedItem(this, e); 49 } 50 51 public void SetSelect(bool bln) 52 { 53 if (bln) 54 { 55 lblTitle.ForeColor = Color.FromArgb(255, 77, 59); 56 ucSplitLine_H1.Visible = true; 57 this.lblTitle.Padding = new Padding(0, 0, 0, 5); 58 } 59 else 60 { 61 lblTitle.ForeColor = Color.FromArgb(64, 64, 64); 62 ucSplitLine_H1.Visible = false; 63 this.lblTitle.Padding = new Padding(0, 0, 0, 0); 64 } 65 } 66 } 67 }