精华内容
下载资源
问答
  • 非常值得收藏,下载的源码资源: 1. 代码源自网络,并添加部分示例代码; 2. 自定义Combobx下拉框,支持基础控件下拉,也支持自定义控件下拉,扩展十分方便;
  • 控件有个DropDownControl属性,你可以指定给这个控件点下拉按钮时弹出datagridview,richTextBox等等系统控件甚至是自己定义的UserControl控件。。。下载后自己看吧,有源码有示例有真像
  • CustomCompleteTextBox 适用于 WinForm 的带下拉列表自定义搜索文本框
  • 主要用的就是停靠窗体了,(十九)c#Winform自定义控件-停靠窗体,不了解的可以先去看一下 思路: 通过实体对象设置的对齐方式来实现左右对齐, 当鼠标进入一项的时候,判断是否弹出下拉列表,或关闭其他列表 开始 ...

    主要用的就是停靠窗体了,(十九)c#Winform自定义控件-停靠窗体,不了解的可以先去看一下

    思路:

    通过实体对象设置的对齐方式来实现左右对齐,

    当鼠标进入一项的时候,判断是否弹出下拉列表,或关闭其他列表

    开始

    添加一个类用来设置节点信息

    复制代码
    1 public class NavigationMenuItem
    2 {
    3 ///
    4 /// The icon
    5 ///
    6 private Image icon;
    7 ///
    8 /// Gets or sets the icon.
    9 ///
    10 /// The icon.
    11 [Description(“图标,仅顶级节点有效”)]
    12 public Image Icon
    13 {
    14 get { return icon; }
    15 set { icon = value; }
    16 }
    17
    18 ///
    19 /// The text
    20 ///
    21 private string text;
    22 ///
    23 /// Gets or sets the text.
    24 ///
    25 /// The text.
    26
    27 [Description(“文本”)]
    28 public string Text
    29 {
    30 get { return text; }
    31 set { text = value; }
    32 }
    33
    34 ///
    35 /// The show tip
    36 ///
    37 private bool showTip;
    38 ///
    39 /// Gets or sets a value indicating whether [show tip].当TipText为空时只显示一个小圆点,否则显示TipText文字
    40 ///
    41 /// true if [show tip]; otherwise, false.
    42 [Description(“是否显示角标,仅顶级节点有效”)]
    43 public bool ShowTip
    44 {
    45 get { return showTip; }
    46 set { showTip = value; }
    47 }
    48
    49 ///
    50 /// The tip text
    51 ///
    52 private string tipText;
    53 ///
    54 /// Gets or sets the tip text
    55 ///
    56 /// The tip text.
    57 [Description(“角标文字,仅顶级节点有效”)]
    58 public string TipText
    59 {
    60 get { return tipText; }
    61 set { tipText = value; }
    62 }
    63 ///
    64 /// The items
    65 ///
    66 private NavigationMenuItem[] items;
    67 ///
    68 /// Gets or sets the items.
    69 ///
    70 /// The items.
    71 [Description(“子项列表”)]
    72 public NavigationMenuItem[] Items
    73 {
    74 get { return items; }
    75 set
    76 {
    77 items = value;
    78 if (value != null)
    79 {
    80 foreach (var item in value)
    81 {
    82 item.ParentItem = this;
    83 }
    84 }
    85 }
    86 }
    87
    88 ///
    89 /// The anchor right
    90 ///
    91 private bool anchorRight;
    92
    93 ///
    94 /// Gets or sets a value indicating whether [anchor right].
    95 ///
    96 /// true if [anchor right]; otherwise, false.
    97 [Description(“是否靠右对齐”)]
    98 public bool AnchorRight
    99 {
    100 get { return anchorRight; }
    101 set { anchorRight = value; }
    102 }
    103
    104 ///
    105 /// The item width
    106 ///
    107 private int itemWidth = 100;
    108
    109 ///
    110 /// Gets or sets the width of the item.
    111 ///
    112 /// The width of the item.
    113 [Description(“宽度”)]
    114 public int ItemWidth
    115 {
    116 get { return itemWidth; }
    117 set { itemWidth = value; }
    118 }
    119
    120 ///
    121 /// Gets or sets the data source.
    122 ///
    123 /// The data source.
    124 [Description(“数据源”)]
    125 public object DataSource { get; set; }
    126 ///
    127 /// Gets or sets a value indicating whether this instance has split lint at top.
    128 ///
    129 /// true if this instance has split lint at top; otherwise, false.
    130 [Description(“是否在此项顶部显示一个分割线”)]
    131 public bool HasSplitLintAtTop { get; set; }
    132
    133 ///
    134 /// Gets the parent item.
    135 ///
    136 /// The parent item.
    137 [Description(“父节点”)]
    138 public NavigationMenuItem ParentItem { get; private set; }
    139 }
    复制代码
    添加一个自定义控件UCNavigationMenu

    添加一些属性

    复制代码
    1 ///
    2 /// Occurs when [click itemed].
    3 ///
    4 [Description(“点击节点事件”), Category(“自定义”)]
    5
    6 public event EventHandler ClickItemed;
    7 ///
    8 /// The select item
    9 ///
    10 private NavigationMenuItem selectItem = null;
    11
    12 ///
    13 /// Gets the select item.
    14 ///
    15 /// The select item.
    16 [Description(“选中的节点”), Category(“自定义”)]
    17 public NavigationMenuItem SelectItem
    18 {
    19 get { return selectItem; }
    20 private set { selectItem = value; }
    21 }
    22
    23
    24 ///
    25 /// The items
    26 ///
    27 NavigationMenuItem[] items;
    28
    29 ///
    30 /// Gets or sets the items.
    31 ///
    32 /// The items.
    33 [Description(“节点列表”), Category(“自定义”)]
    34 public NavigationMenuItem[] Items
    35 {
    36 get { return items; }
    37 set
    38 {
    39 items = value;
    40 ReloadMenu();
    41 }
    42 }
    43
    44 ///
    45 /// The tip color
    46 ///
    47 private Color tipColor = Color.FromArgb(255, 87, 34);
    48
    49 ///
    50 /// Gets or sets the color of the tip.
    51 ///
    52 /// The color of the tip.
    53 [Description(“角标颜色”), Category(“自定义”)]
    54 public Color TipColor
    55 {
    56 get { return tipColor; }
    57 set { tipColor = value; }
    58 }
    59
    60 ///
    61 /// 获取或设置控件的前景色。
    62 ///
    63 /// The color of the fore.
    64 ///
    65 ///
    66 ///
    67 public override System.Drawing.Color ForeColor
    68 {
    69 get
    70 {
    71 return base.ForeColor;
    72 }
    73 set
    74 {
    75 base.ForeColor = value;
    76 foreach (Control c in this.Controls)
    77 {
    78 c.ForeColor = value;
    79 }
    80 }
    81 }
    82 ///
    83 /// 获取或设置控件显示的文字的字体。
    84 ///
    85 /// The font.
    86 ///
    87 ///
    88 ///
    89 ///
    90 ///
    91 ///
    92 public override Font Font
    93 {
    94 get
    95 {
    96 return base.Font;
    97 }
    98 set
    99 {
    100 base.Font = value;
    101 foreach (Control c in this.Controls)
    102 {
    103 c.Font = value;
    104 }
    105 }
    106 }
    107
    108 ///
    109 /// The m LST anchors
    110 ///
    111 Dictionary<NavigationMenuItem, FrmAnchor> m_lstAnchors = new Dictionary<NavigationMenuItem, FrmAnchor>();
    复制代码
    重载菜单

    复制代码
    1 private void ReloadMenu()
    2 {
    3 try
    4 {
    5 ControlHelper.FreezeControl(this, true);
    6 this.Controls.Clear();
    7 if (items != null && items.Length > 0)
    8 {
    9 foreach (var item in items)
    10 {
    11 var menu = (NavigationMenuItem)item;
    12 Label lbl = new Label();
    13 lbl.AutoSize = false;
    14 lbl.TextAlign = ContentAlignment.MiddleCenter;
    15 lbl.Width = menu.ItemWidth;
    16 lbl.Text = menu.Text;
    17
    18 lbl.Font = Font;
    19 lbl.ForeColor = ForeColor;
    20
    21 lbl.Paint += lbl_Paint;
    22 lbl.MouseEnter += lbl_MouseEnter;
    23 lbl.Tag = menu;
    24 lbl.Click += lbl_Click;
    25 if (menu.AnchorRight)
    26 {
    27 lbl.Dock = DockStyle.Right;
    28 }
    29 else
    30 {
    31 lbl.Dock = DockStyle.Left;
    32 }
    33 this.Controls.Add(lbl);
    34
    35 lbl.BringToFront();
    36 }
    37
    38
    39 }
    40 }
    41 finally
    42 {
    43 ControlHelper.FreezeControl(this, false);
    44 }
    45 }
    复制代码
    显示下级菜单

    复制代码
    1 private void ShowMoreMenu(Label lbl)
    2 {
    3 var menu = (NavigationMenuItem)lbl.Tag;
    4 if (CheckShow(menu))
    5 {
    6 if (menu.Items != null && menu.Items.Length > 0)
    7 {
    8 Panel panel = new Panel();
    9 panel.BackColor = Color.White;
    10 panel.Paint += panel_Paint;
    11 panel.Padding = new System.Windows.Forms.Padding(1);
    12 Size size = GetItemsSize(menu.Items);
    13 var height = size.Height * menu.Items.Length + 2;
    14 height += menu.Items.Count(p => p.HasSplitLintAtTop);//分割线
    15 if (size.Width < lbl.Width)
    16 size.Width = lbl.Width;
    17 panel.Size = new Size(size.Width, height);
    18
    19 foreach (var item in menu.Items)
    20 {
    21 if (item.HasSplitLintAtTop)
    22 {
    23 UCSplitLine_H line = new UCSplitLine_H();
    24 line.Dock = DockStyle.Top;
    25 panel.Controls.Add(line);
    26 line.BringToFront();
    27 }
    28 Label _lbl = new Label();
    29 _lbl.Font = Font;
    30 _lbl.ForeColor = this.BackColor;
    31 _lbl.AutoSize = false;
    32 _lbl.TextAlign = ContentAlignment.MiddleCenter;
    33 _lbl.Height = size.Height;
    34 _lbl.Text = item.Text;
    35 _lbl.Dock = DockStyle.Top;
    36 _lbl.BringToFront();
    37 _lbl.Paint += lbl_Paint;
    38 _lbl.MouseEnter += lbl_MouseEnter;
    39 _lbl.Tag = item;
    40 _lbl.Click += lbl_Click;
    41 _lbl.Size = new System.Drawing.Size(size.Width, size.Height);
    42 panel.Controls.Add(_lbl);
    43 _lbl.BringToFront();
    44 }
    45 Point point = Point.Empty;
    46
    47 if (menu.ParentItem != null)
    48 {
    49 Point p = lbl.Parent.PointToScreen(lbl.Location);
    50 if (p.X + lbl.Width + panel.Width > Screen.PrimaryScreen.Bounds.Width)
    51 {
    52 point = new Point(-1 * panel.Width - 2, -1 * lbl.Height);
    53 }
    54 else
    55 {
    56 point = new Point(panel.Width + 2, -1 * lbl.Height);
    57 }
    58 }
    59 m_lstAnchors[menu] = new FrmAnchor(lbl, panel, point);
    60 m_lstAnchors[menu].FormClosing += UCNavigationMenu_FormClosing;
    61 m_lstAnchors[menu].Show();
    62 m_lstAnchors[menu].Size = new Size(size.Width, height);
    63 }
    64 }
    65
    66 }
    复制代码
    辅助函数

    复制代码
    1 ///
    2 /// Checks the show.
    3 ///
    4 /// The menu.
    5 /// true if XXXX, false otherwise.
    6 private bool CheckShow(NavigationMenuItem menu)
    7 {
    8 //检查已经打开的节点
    9 if (m_lstAnchors.ContainsKey(menu))
    10 {
    11 CloseList(menu);
    12 return false;
    13 }
    14 if (HasInCacheChild(menu))
    15 {
    16 if (m_lstAnchors.ContainsKey(menu.ParentItem))
    17 {
    18 CloseList(menu.ParentItem);
    19 return true;
    20 }
    21 return false;
    22 }
    23 else
    24 {
    25 for (int i = 0; i < 1; )
    26 {
    27 try
    28 {
    29 foreach (var item in m_lstAnchors)
    30 {
    31 if (m_lstAnchors[item.Key] != null && !m_lstAnchors[item.Key].IsDisposed)
    32 {
    33 m_lstAnchors[item.Key].Close();
    34 }
    35 }
    36 }
    37 catch
    38 {
    39 continue;
    40 }
    41 i++;
    42 }
    43 m_lstAnchors.Clear();
    44 return true;
    45 }
    46 }
    47
    48 ///
    49 /// Determines whether [has in cache child] [the specified menu].
    50 ///
    51 /// The menu.
    52 /// true if [has in cache child] [the specified menu]; otherwise, false.
    53 private bool HasInCacheChild(NavigationMenuItem menu)
    54 {
    55 foreach (var item in m_lstAnchors)
    56 {
    57 if (item.Key == menu)
    58 {
    59 return true;
    60 }
    61 else
    62 {
    63 if (item.Key.Items != null)
    64 {
    65 if (item.Key.Items.Contains(menu))
    66 return true;
    67 }
    68 }
    69 }
    70 return false;
    71 }
    72
    73 ///
    74 /// Closes the list.
    75 ///
    76 /// The menu.
    77 private void CloseList(NavigationMenuItem menu)
    78 {
    79 if (menu.Items != null)
    80 {
    81 foreach (var item in menu.Items)
    82 {
    83 CloseList(item);
    84 if (m_lstAnchors.ContainsKey(item))
    85 {
    86 if (m_lstAnchors[item] != null && !m_lstAnchors[item].IsDisposed)
    87 {
    88 m_lstAnchors[item].Close();
    89 m_lstAnchors[item] = null;
    90 m_lstAnchors.Remove(item);
    91 }
    92 }
    93 }
    94 }
    95 }
    复制代码
    一些事件

    复制代码
    1 ///
    2 /// Handles the Click event of the lbl control.
    3 ///
    4 /// The source of the event.
    5 /// The instance containing the event data.
    6 void lbl_Click(object sender, EventArgs e)
    7 {
    8 Label lbl = sender as Label;
    9 if (lbl.Tag != null)
    10 {
    11 var menu = (NavigationMenuItem)lbl.Tag;
    12 if (menu.Items == null || menu.Items.Length <= 0)
    13 {
    14 selectItem = menu;
    15
    16 while (m_lstAnchors.Count > 0)
    17 {
    18 try
    19 {
    20 foreach (var item in m_lstAnchors)
    21 {
    22 item.Value.Close();
    23 m_lstAnchors.Remove(item.Key);
    24 }
    25 }
    26 catch { }
    27 }
    28
    29 if (ClickItemed != null)
    30 {
    31 ClickItemed(this, e);
    32 }
    33 }
    34 else
    35 {
    36 CloseList(menu);
    37 if (m_lstAnchors.ContainsKey(menu))
    38 {
    39 if (m_lstAnchors[menu] != null && !m_lstAnchors[menu].IsDisposed)
    40 {
    41 m_lstAnchors[menu].Close();
    42 }
    43 m_lstAnchors.Remove(menu);
    44 }
    45 ShowMoreMenu(lbl);
    46 }
    47 }
    48 }
    49
    50 ///
    51 /// Handles the MouseEnter event of the lbl control.
    52 ///
    53 /// The source of the event.
    54 /// The instance containing the event data.
    55 void lbl_MouseEnter(object sender, EventArgs e)
    56 {
    57 Label lbl = sender as Label;
    58 ShowMoreMenu(lbl);
    59 }
    60 ///
    61 /// Handles the FormClosing event of the UCNavigationMenu control.
    62 ///
    63 /// The source of the event.
    64 /// The instance containing the event data.
    65 void UCNavigationMenu_FormClosing(object sender, FormClosingEventArgs e)
    66 {
    67 FrmAnchor frm = sender as FrmAnchor;
    68 if (m_lstAnchors.ContainsValue(frm))
    69 {
    70 foreach (var item in m_lstAnchors)
    71 {
    72 if (item.Value == frm)
    73 {
    74 m_lstAnchors.Remove(item.Key);
    75 return;
    76 }
    77 }
    78 }
    79 }
    80
    81 ///
    82 /// Handles the Paint event of the panel control.
    83 ///
    84 /// The source of the event.
    85 /// The instance containing the event data.
    86 void panel_Paint(object sender, PaintEventArgs e)
    87 {
    88 e.Graphics.SetGDIHigh();
    89 Rectangle rect = new Rectangle(0, 0, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
    90 var path = rect.CreateRoundedRectanglePath(2);
    91 e.Graphics.DrawPath(new Pen(new SolidBrush(LineColors.Light)), path);
    92 }
    93
    94
    95
    96 ///
    97 /// Gets the size of the items.
    98 ///
    99 /// The items.
    100 /// Size.
    101 private Size GetItemsSize(NavigationMenuItem[] items)
    102 {
    103 Size size = Size.Empty;
    104 if (items != null && items.Length > 0)
    105 {
    106 using (var g = this.CreateGraphics())
    107 {
    108 foreach (NavigationMenuItem item in items)
    109 {
    110 var s = g.MeasureString(item.Text, Font);
    111 if (s.Width + 25 > size.Width)
    112 {
    113 size.Width = (int)s.Width + 25;
    114 }
    115 if (s.Height + 10 > size.Height)
    116 {
    117 size.Height = (int)s.Height + 10;
    118 }
    119 }
    120 }
    121 }
    122 return size;
    123 }
    124
    125
    126 ///
    127 /// Handles the Paint event of the lbl control.
    128 ///
    129 /// The source of the event.
    130 /// The instance containing the event data.
    131 void lbl_Paint(object sender, PaintEventArgs e)
    132 {
    133 Label lbl = sender as Label;
    134 if (lbl.Tag != null)
    135 {
    136 var menu = (NavigationMenuItem)lbl.Tag;
    137 e.Graphics.SetGDIHigh();
    138 if (menu.ParentItem == null)//顶级节点支持图标和角标
    139 {
    140 if (menu.ShowTip)
    141 {
    142 if (!string.IsNullOrEmpty(menu.TipText))
    143 {
    144 var rect = new Rectangle(lbl.Width - 25, lbl.Height / 2 - 10, 20, 20);
    145 var path = rect.CreateRoundedRectanglePath(5);
    146 e.Graphics.FillPath(new SolidBrush(tipColor), path);
    147 e.Graphics.DrawString(menu.TipText, new Font(“微软雅黑”, 8f), new SolidBrush(Color.White), rect, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
    148 }
    149 else
    150 {
    151 e.Graphics.FillEllipse(new SolidBrush(tipColor), new Rectangle(lbl.Width - 20, lbl.Height / 2 - 10, 10, 10));
    152 }
    153 }
    154 if (menu.Icon != null)
    155 {
    156 e.Graphics.DrawImage(menu.Icon, new Rectangle(1, (lbl.Height - 25) / 2, 25, 25), 0, 0, menu.Icon.Width, menu.Icon.Height, GraphicsUnit.Pixel);
    157 }
    158 }
    159 if (menu.ParentItem != null && menu.Items != null && menu.Items.Length > 0)
    160 {
    161 ControlHelper.PaintTriangle(e.Graphics, new SolidBrush(this.BackColor), new Point(lbl.Width - 11, (lbl.Height - 5) / 2), 5, GraphDirection.Rightward);
    162 }
    163 }
    164 }
    复制代码
    深圳网站建设www.sz886.com

    展开全文
  • DataTable QYu = myDataSet.Tables[0].DefaultView.ToTable(true, "_QYU"); //DataView view = new DataView(QYu); DataRow row = QYu.NewRow(); row["_QYU"] = "选区域";...AQYu.DataSource = Q
     
    DataTable QYu = myDataSet.Tables[0].DefaultView.ToTable(true, "_QYU");
    //DataView view = new DataView(QYu);
    DataRow row = QYu.NewRow();
    row["_QYU"] = "选区域";
    QYu.Rows.Add(row);
    AQYu.DataSource = QYu;//获取不重复的值
    AQYu.DisplayMember = "_QYU";
    AQYu.ValueMember = "_QYU";
    AQYu.Text = "选区域";//最后设置就可以在加载首次显示
    展开全文
  • winform 下拉框(自定义下拉框控件)

    千次阅读 2020-06-08 19:51:56
    项目中遇到需要下拉框列表内容为线类型或点类型图形的需求,想到可以使用手绘线条和图形的方式来实现下拉列表内容自定义,记录下来供大家参考学习之用。 在项目中添加一个组件 添加完之后会显示如下设计界面 这里...

    项目中遇到需要下拉框列表内容为线类型或点类型图形的需求,想到可以使用手绘线条和图形的方式来实现下拉列表内容自定义,记录下来供大家参考学习之用。

    在项目中添加一个组件

    在这里插入图片描述

    在这里插入图片描述
    添加完之后会显示如下设计界面
    在这里插入图片描述
    这里直接点击切换到代码视图即可

    注意:新建的组件默认继承Component,我们这里是要自定义一个ComboBox下拉框,所以要继承自ComboBox,此类位于using System.Windows.Forms命名空间下
    在这里插入图片描述

    线的类型列表

    在这里插入图片描述

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace CustomComponents
    {
        /// <summary>
        /// 填充线型
        /// </summary>
        public partial class FillLineTypeCbo : ComboBox
        {
            public FillLineTypeCbo()
            {
          		//初始化组件
                InitializeComponent();
            }
    
            public FillLineTypeCbo(IContainer container)
            {
                container.Add(this);
    
                InitializeComponent();
                InitItems();
            }
    
            private void InitItems()
            {
                this.DrawMode = DrawMode.OwnerDrawFixed;//手动绘制所有元素
                this.DropDownStyle = ComboBoxStyle.DropDownList;//下拉框样式设置为不能编辑
                this.Items.Clear();//清空原有项 
            }
    
            public enum LineType
            {
                DoubleHorizontalLine = 0,//双横线
                VerticalLine,//垂直线
                LeftSlash,//左斜线
                RightSlash,//右斜线
                VerticalGridlines,//垂直网格线
                CrossGridlines,//交叉网格线
                SolidBrush,//实心刷
                HollowBrush,//空心刷
            }
            //protected
            protected override void OnDrawItem(DrawItemEventArgs e)
            {
                if (e.Index >= 0)//判断是否需要重绘
                {
                    int typeId = int.Parse(this.Items[e.Index].ToString());//获取选项id
    
                    Font font = new Font("宋体", 9);//定义字体
                    Rectangle rect = e.Bounds;
                    //rect.Inflate(-2, -2);//缩放一定大小
                    rect.Inflate(5, -2);//缩放一定大小
                    Pen pen = null;
                    SolidBrush solidBrush = new SolidBrush(Color.Black);
    
                    float offSet = rect.Height / 2;
                    float x = rect.Width / 10;
                    float y = rect.Top + offSet;//如果设置成e.ItemHeigh*e.Index +offSet,则在选中节点后,由于Item位置固定,因此Item不能显示出来。
                    switch (typeId)
                    {
                        case (int)LineType.DoubleHorizontalLine:
                            pen = new Pen(Color.Black, 1);
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(8 * x, y));//绘制水平线
                            e.Graphics.DrawLine(pen, new PointF(x, y + 5), new PointF(8 * x, y + 5));
                            //e.Graphics.DrawLine(pen, new PointF(x, y+2), new PointF(x, y+2));
                            break;
                        case (int)LineType.VerticalLine:
                            pen = new Pen(Color.Black, 1);
                            //绘制垂直线
                            int xNum = 0;
                            for (int i = 0; i < 10; i++)
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNum, y - 4), new PointF(1 * x + xNum, y + 6));
                                xNum += 7;
    
                            }
                            break;
                        case (int)LineType.LeftSlash:
                            pen = new Pen(Color.Black, 1);
                            //绘制左斜线
                            int xNumLeftSlash = 0;
                            for (int i = 0; i < 10; i++)
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNumLeftSlash, y - 4), new PointF(x + 5 + xNumLeftSlash, y + 7));
                                xNumLeftSlash += 7;
                            }
                            break;
                        case (int)LineType.RightSlash:
                            pen = new Pen(Color.Black, 1);
                            //绘制右斜线
                            int xNumRightSlash = 0;
                            for (int i = 0; i < 10; i++)
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNumRightSlash + 7, y - 4), new PointF(x + xNumRightSlash, y + 7));
                                xNumRightSlash += 7;
                            }
                            break;
                        case (int)LineType.VerticalGridlines:
                            pen = new Pen(Color.Black, 1);
                            //绘制垂直网格线
                            xNum = 0;
                            for (int i = 0; i < 10; i++)//绘制竖线
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNum, y - 4), new PointF(1 * x + xNum, y + 6));
                                xNum += 7;
                            }
                            //绘制双横线
                            e.Graphics.DrawLine(pen, new PointF(x - 3, y - 2), new PointF(8 * x, y - 2));
                            e.Graphics.DrawLine(pen, new PointF(x - 3, y + 5), new PointF(8 * x, y + 5));
                            break;
                        case (int)LineType.CrossGridlines:
                            pen = new Pen(Color.Black, 1);
                            //绘制交叉网格线
                            //绘制左斜线
                            xNumLeftSlash = 0;
                            for (int i = 0; i < 10; i++)
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNumLeftSlash, y - 4), new PointF(x + 10 + xNumLeftSlash, y + 7));
                                xNumLeftSlash += 7;
                            }
                            //绘制右斜线
                            xNumRightSlash = 0;
                            for (int i = 0; i < 10; i++)
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNumRightSlash + 10, y - 4), new PointF(x + xNumRightSlash, y + 7));
                                xNumRightSlash += 7;
                            }
                            break;
                        case (int)LineType.SolidBrush:
                            pen = new Pen(Color.Black, 10);
                            //绘制实心刷
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(8 * x, y));
                            break;
                        case (int)LineType.HollowBrush:
                            pen = new Pen(Color.Black, 1);
                            //绘制空心刷
                            e.Graphics.DrawLine(pen, new PointF(x, y - 6), new PointF(x, y + 6));//左
                            e.Graphics.DrawLine(pen, new PointF(x, y - 6), new PointF(8 * x, y - 6));//上
                            e.Graphics.DrawLine(pen, new PointF(8 * x, y - 6), new PointF(8 * x, y + 6));//右
                            e.Graphics.DrawLine(pen, new PointF(x, y + 6), new PointF(8 * x, y + 6));//下
                            break;
                        default:
                            pen = new Pen(Color.Black, 1);
                            break;
                    }
                }
            }
        }
    }
    
    

    边框线类型列表

    在这里插入图片描述

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace CustomComponents
    {
        /// <summary>
        /// 线型
        /// </summary>
        public partial class LineShapeCbo : ComboBox
        {
            public LineShapeCbo()
            {
                InitializeComponent();
            }
    
            public LineShapeCbo(IContainer container)
            {
                container.Add(this);
    
                InitializeComponent();
                InitItems();
            }
    
            private void InitItems()
            {
                this.DrawMode = DrawMode.OwnerDrawFixed;//手动绘制所有元素
                this.DropDownStyle = ComboBoxStyle.DropDownList;//下拉框样式设置为不能编辑
                this.Items.Clear();//清空原有项 
            }
    
            public enum LineType
            {
                SolidLine = 0,//实线
                LongDisconnection,//长间断线
                ShortEndLine,//短间端线
                LongAndShort,//长短相间
                ShortToLong,//长短短相间
                EmptyBrushes//空画笔
            }
    
            protected override void OnDrawItem(DrawItemEventArgs e)
            {
                if (e.Index >= 0)//判断是否需要重绘
                {
                    int typeId = int.Parse(this.Items[e.Index].ToString());//获取选项id
    
                    Font font = new Font("宋体", 9);//定义字体
                    Rectangle rect = e.Bounds;
                    //rect.Inflate(-2, -2);//缩放一定大小
                    rect.Inflate(5, -2);//缩放一定大小
                    Pen pen = null;
                    SolidBrush solidBrush = new SolidBrush(Color.Black);
    
                    float offSet = rect.Height / 2;
                    float x = rect.Width / 10;
                    float y = rect.Top + offSet;//如果设置成e.ItemHeigh*e.Index +offSet,则在选中节点后,由于Item位置固定,因此Item不能显示出来。
                    switch (typeId)
                    {
                        case (int)LineType.SolidLine:
                            pen = new Pen(Color.Black, 1);
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(8 * x, y));//绘制实线
                            //e.Graphics.DrawLine(pen, new PointF(x, y+2), new PointF(x, y+2));
                            break;
                        case (int)LineType.LongDisconnection:
                            pen = new Pen(Color.Black, 1);
                            //绘制长间断线
                            int xNum = 0;
                            for (int i = 0; i < 3; i++)
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNum, y), new PointF(15+x + xNum, y));
                                xNum += 20;
                            }
                            e.Graphics.DrawLine(pen, new PointF(x + xNum, y), new PointF(10 + x + xNum, y));
                            break;
                        case (int)LineType.ShortEndLine:
                            pen = new Pen(Color.Black, 1);
                            //绘制短间端线
                            xNum = 0;
                            for (int i = 0; i < 8; i++)
                            {
                                e.Graphics.DrawLine(pen, new PointF(x + xNum, y), new PointF(6 + x + xNum, y));
                                xNum += 9;
                            }
                            break;
                        case (int)LineType.LongAndShort:
                            pen = new Pen(Color.Black, 1);
                            //绘制长短相间
                                e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(x+10, y));
                                e.Graphics.DrawLine(pen, new PointF(x+15, y), new PointF(x+20, y));
                                e.Graphics.DrawLine(pen, new PointF(x+25, y), new PointF(x+35, y));
                                e.Graphics.DrawLine(pen, new PointF(x+40, y), new PointF(x+45, y));
                                e.Graphics.DrawLine(pen, new PointF(x+50, y), new PointF(x+60, y));
                                e.Graphics.DrawLine(pen, new PointF(x+65, y), new PointF(x+70, y));
                            break;
                        case (int)LineType.ShortToLong:
                            pen = new Pen(Color.Black, 1);
                            //绘制长短短相间
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(x + 10, y));
                            e.Graphics.DrawLine(pen, new PointF(x+15, y), new PointF(x + 18, y));
                            e.Graphics.DrawLine(pen, new PointF(x+23, y), new PointF(x + 26, y));
                            e.Graphics.DrawLine(pen, new PointF(x+31, y), new PointF(x + 41, y));
                            e.Graphics.DrawLine(pen, new PointF(x + 46, y), new PointF(x + 49, y));
                            e.Graphics.DrawLine(pen, new PointF(x + 54, y), new PointF(x + 57, y));
                            e.Graphics.DrawLine(pen, new PointF(x + 62, y), new PointF(x + 70, y));
                            break;
                        case (int)LineType.EmptyBrushes:
                            pen = new Pen(Color.Black, 1);
                            //绘制空画笔
                            break;
                        //case (int)LineType.LineWithPoints:
                        default:
                            pen = new Pen(Color.Black, 1);
                            break;
                    }
                    //if (e.Index < 9)
                    //{
                    //    e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(8 * x, y));//绘制线
                    //    //Rectangle rectColor = new Rectangle(rect.Location, new Size(9 * (int)x, rect.Height));
                    //    //e.Graphics.DrawRectangle(Pens.Black, rectColor);//绘制边框
                    //}
                }
            }
        }
    }
    
    

    点类型列表

    在这里插入图片描述

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace CustomComponents
    {
        /// <summary>
        /// 点类型
        /// </summary>
        public partial class PointTypeCbo : ComboBox
        {
            public PointTypeCbo()
            {
                InitializeComponent();
            }
    
            public PointTypeCbo(IContainer container)
            {
                container.Add(this);
    
                InitializeComponent();
                InitItems();
            }
            private void InitItems()
            {
                this.DrawMode = DrawMode.OwnerDrawFixed;//手动绘制所有元素
                this.DropDownStyle = ComboBoxStyle.DropDownList;//下拉框样式设置为不能编辑
                this.Items.Clear();//清空原有项 
            }
    
            protected override void OnDrawItem(DrawItemEventArgs e)
            {
                if (e.Index >= 0)//判断是否需要重绘
                {
                    int typeId = int.Parse(this.Items[e.Index].ToString());//获取选项id
    
                    Font font = new Font("宋体", 9);//定义字体
                    Rectangle rect = e.Bounds;
                    //rect.Inflate(-2, -2);//缩放一定大小
                    rect.Inflate(5, -2);//缩放一定大小
                    Pen pen = null;
                    SolidBrush solidBrush = new SolidBrush(Color.Black);
    
                    float offSet = rect.Height / 2;
                    float x = rect.Width / 10;
                    float y = rect.Top + offSet;//如果设置成e.ItemHeigh*e.Index +offSet,则在选中节点后,由于Item位置固定,因此Item不能显示出来。
                    switch (typeId)
                    {
                        case 0:
                            pen = new Pen(Color.Red, 1);//设置边框
                            //SolidBrush sb0 = new SolidBrush(Color.Black);//设置填充颜色
                            //绘制
                            //e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(8 * x, y));
                            //Graphics g = CreateGraphics();
                            //Brush myBrush = new SolidBrush(Color.Green);
                            //string str = "just for fun";
                            //Font myFont = new Font("宋体", 9, FontStyle.Bold);
                            //e.Graphics.DrawString(str, myFont, myBrush, 60, 20);          
                            //e.Graphics.FillEllipse(sb0, 10 ,10 , 10, 10);
                            e.Graphics.DrawEllipse(pen, 9, 5, 10, 10);
                            break;
                        case 1:
                            pen = new Pen(Color.Red, 1);
                            //绘制正方形
                            e.Graphics.DrawLine(pen, new PointF(x, y - 5), new PointF(x, y + 5));//左
                            e.Graphics.DrawLine(pen, new PointF(x, y - 5), new PointF(x + 10, y - 5));//上
                            e.Graphics.DrawLine(pen, new PointF(x + 10, y - 5), new PointF(x + 10, y + 5));//右
                            e.Graphics.DrawLine(pen, new PointF(x, y + 5), new PointF(x + 10, y + 5));//下
    
                            //Rectangle rectColor = new Rectangle(rect.Location, new Size(10, 10));
                            //e.Graphics.DrawRectangle(Pens.Black, rectColor);//绘制边框
    
                            break;
                        case 2:
                            pen = new Pen(Color.Red, 1);
                            //绘制十字形
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(x + 10, y));//横
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y - 5), new PointF(x + 5, y + 5));//竖
                            break;
                        case 3:
                            pen = new Pen(Color.Red, 1);
                            //绘制三角形
                            e.Graphics.DrawLine(pen, new PointF(x, y + 5), new PointF(x + 5, y - 5));//左
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y - 5), new PointF(x + 10, y + 5));//右
                            e.Graphics.DrawLine(pen, new PointF(x, y + 5), new PointF(x + 10, y + 5));//下
                            break;
                        case 4:
                            pen = new Pen(Color.Red, 1);
                            //绘制右(三角)红旗
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y + 5), new PointF(x + 5, y - 5));//竖杆
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y - 5), new PointF(x + 10, y));//红旗右边
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y), new PointF(x + 10, y));//红旗下边
                            break;
                        case 5:
                            pen = new Pen(Color.Red, 1);
                            //绘制左(三角)红旗 
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y + 5), new PointF(x + 5, y - 5));//竖杆
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(x + 5, y - 5));//红旗左边
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(x + 5, y));//红旗下边
                            break;
                        case 6:
                            pen = new Pen(Color.Red, 1);
                            //绘制右方旗
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y + 5), new PointF(x + 5, y - 5));//竖杆
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y - 5), new PointF(x + 10, y - 5));//右上边
                            e.Graphics.DrawLine(pen, new PointF(x + 10, y - 5), new PointF(x + 10, y));//右右边
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y), new PointF(x + 10, y));//右下边
                            break;
                        case 7:
                            pen = new Pen(Color.Red, 1);
                            //绘制大圆包小圆
                            //e.Graphics.DrawEllipse(pen, 20, 115, 10, 10);//空心大圆
                            //e.Graphics.DrawEllipse(pen, 13, 118, 4, 4);//空心小圆 
                            e.Graphics.DrawEllipse(pen, x, y - 5, 10, 10);//空心大圆
                            e.Graphics.DrawEllipse(pen, x + 3, y - 5 + 3, 4, 4);//空心小圆
                            //Rectangle rectColor = new Rectangle(rect.Location, new Size(9 * (int)x, rect.Height));
                            //e.Graphics.DrawRectangle(Pens.Black, rectColor);//绘制边框
                            break;
                        case 8:
                            pen = new Pen(Color.Red, 1);
                            //绘制大圆加十字
                            e.Graphics.DrawEllipse(pen, x, y - 5, 10, 10);//空心大圆
                            //绘制十字形
                            e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(x + 10, y));//横
                            e.Graphics.DrawLine(pen, new PointF(x + 5, y - 5), new PointF(x + 5, y + 5));//竖
                            break;
                        case 9:
                            pen = new Pen(Color.Red, 1);
                            //绘制实心圆
                            SolidBrush sb9 = new SolidBrush(Color.Green);//设置填充颜色
                            e.Graphics.DrawEllipse(pen, x, y - 5, 10, 10);//实心圆边框
                            e.Graphics.FillEllipse(sb9, x, y - 5, 10, 10);//实心圆填充
                            break;
                        case 10:
                            pen = new Pen(Color.Red, 1);
                            //绘制实心正方形
                            //绘制正方形
                            e.Graphics.DrawRectangle(pen, x, y - 5, 10, 10);
                            SolidBrush sb10 = new SolidBrush(Color.Green);//设置填充颜色
                            e.Graphics.FillRectangle(sb10, x, y - 5, 10, 10);
                            break;
                        case 11:
                            pen = new Pen(Color.Red, 1);
                            //绘制
                            PointF p1 = new PointF(x + 5, y - 5);
                            PointF p2 = new PointF(x, y + 5);
                            PointF p3 = new PointF(x + 10, y + 5);
                            PointF[] points = new PointF[3];
                            Brush myBrush = new SolidBrush(Color.Green);
                            points[0] = p1;
                            points[1] = p2;
                            points[2] = p3;
                            e.Graphics.FillPolygon(myBrush, points, FillMode.Alternate);
                            e.Graphics.DrawPolygon(pen, points);
                            break;
                        //case (int)LineType.LineWithPoints:
                        default:
                            pen = new Pen(Color.Black, 1);
                            break;
                    }
                    if (e.Index < 12)
                    {
                        //e.Graphics.DrawLine(pen, new PointF(x, y), new PointF(8 * x, y));//绘制线
                        //设置后面的字符串
                        Rectangle Rect = new Rectangle(rect.Location, new Size(5 * (int)x, rect.Height));
    
                        //文本内容显示区域
                        Rectangle textRect =
                                new Rectangle(Rect.Right + 2, Rect.Y, e.Bounds.Width - Rect.Width, e.Bounds.Height - 2);
    
                        //文本格式垂直居中
                        StringFormat strFormat = new StringFormat();
                        strFormat.LineAlignment = StringAlignment.Center;
                        e.Graphics.DrawString((e.Index + 1).ToString(), new Font("微软雅黑", 12), Brushes.Black, textRect, strFormat);
                    }
                }
            }
        }
    }
    
    

    带图片的列表

    在这里插入图片描述

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace ShowState
    {
        /// <summary>
        /// 下拉框  下拉列表 图片显示
        /// </summary>
        public partial class ComboBoxImg : ComboBox
        {
            public ComboBoxImg()
            {
                InitializeComponent();
                DrawMode = DrawMode.OwnerDrawFixed;
                DropDownStyle = ComboBoxStyle.DropDownList;
                ItemHeight = 50;
                Width = 40;
            }
    
            public ComboBoxImg(IContainer container)
            {
                container.Add(this);
                InitializeComponent();
    
                DrawMode = DrawMode.OwnerDrawFixed;
                DropDownStyle = ComboBoxStyle.DropDownList;
                ItemHeight = 200;
                Width = 40;
            }
    
            protected override void OnDrawItem(DrawItemEventArgs e)
            {
                if (Items.Count == 0 || e.Index == -1)
                    return;
                if ((e.State & DrawItemState.Selected) != 0)
                {
                    //渐变画刷
                    LinearGradientBrush brush = new LinearGradientBrush(e.Bounds, Color.FromArgb(255, 251, 237),
                                                     Color.FromArgb(255, 236, 181), LinearGradientMode.Vertical);
                    //填充区域
                    Rectangle borderRect = new Rectangle(3, e.Bounds.Y, e.Bounds.Width - 5, e.Bounds.Height - 2);
    
                    e.Graphics.FillRectangle(brush, borderRect);
    
                    //画边框
                    Pen pen = new Pen(Color.FromArgb(229, 195, 101));
                    e.Graphics.DrawRectangle(pen, borderRect);
                }
                else
                {
                    SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 255));
                    e.Graphics.FillRectangle(brush, e.Bounds);
                }
    
                //获得项图片,绘制图片
                ItemEx item = (ItemEx)Items[e.Index];
                Image img = item.Image;
    
                //图片绘制的区域
                Rectangle imgRect = new Rectangle(6, e.Bounds.Y + 3, 45, 45);
                e.Graphics.DrawImage(img, imgRect);
    
                //文本内容显示区域
                Rectangle textRect =
                        new Rectangle(imgRect.Right + 2, imgRect.Y, e.Bounds.Width - imgRect.Width, e.Bounds.Height - 2);
    
                //获得项文本内容,绘制文本
                String itemText = Items[e.Index].ToString();
    
                //文本格式垂直居中
                StringFormat strFormat = new StringFormat();
                strFormat.LineAlignment = StringAlignment.Center;
                e.Graphics.DrawString(itemText, new Font("微软雅黑", 12), Brushes.Black, textRect, strFormat);
                base.OnDrawItem(e);
            }
    
        }
    
        /// <summary>
        /// 下拉框  下拉列表 图片显示
        /// </summary>
        public class ItemEx
        {
            /// <summary>
            /// 图片显示
            /// </summary>
            /// <param name="text">文本</param>
            /// <param name="img">图片(图片路径)</param>
            public ItemEx(string text, Image img)
            {
                Text = text;
                Image = img;
            }
    
            public string Text { get; set; }
            public Image Image { get; set; }
    
            public override string ToString()
            {
                return Text;
            }
        }
    }
    
    

    组件编写完之后,进入工具箱,就能看到当前项目中我们自定义的组件了,使用方法跟普通控件方法完全相同,直接拖到窗体即可

    在这里插入图片描述

    展开全文
  • 这一节给大家演示一个具有多选功能的下拉列表框,其实就是一个文本框和checkboxlist组合实现的用户控件,换个角度来实现自定义控件。 先来看下效果图吧,我会分几个步骤来具体讲解这个文本框的实现。    1.界面...
          这一节给大家演示一个具有多选功能的下拉列表框,其实就是一个文本框和checkboxlist组合实现的用户控件,换个角度来实现自定义控件。
    

    先来看下效果图吧,我会分几个步骤来具体讲解这个文本框的实现。

                                            

        1.界面实现

         我们先来看下界面效果怎样实现,然后再讲解具体的功能性实现。

          先创建一个用户控件,当然是继承UserControl类,这个界面需要用到以下控件来实现

         下拉按钮:是一个button控件

         文本框:显示选中的内容,

         多选列表框: checkboxlist

         全选/取消:是两个LABEL控件

          右下角的黑三角:是一个LABEL控件,可实现拉长下拉列表框.

          窗体:点击下拉按钮,实际是弹出一个窗体,下拉列表框中的控件都在这个窗体中显示

        首先看下下拉按钮的实现

       

    /// <summary>
        /// 重写BUTTON
        /// </summary>
        public class ButtonS : Button
        {
            public ButtonS()
            {
                //防止重绘控件出现闪烁
                this.SetStyle(ControlStyles.UserPaint, true);
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
                this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            }
            ButtonState state;
            //当按钮被按下
            protected override void OnMouseDown(MouseEventArgs mevent)
            {
                state = ButtonState.Pushed;
                base.OnMouseDown(mevent);
            }
    
            //当按钮被释放
            protected override void OnMouseUp(MouseEventArgs mevent)
            {
                state = ButtonState.Normal;
                base.OnMouseUp(mevent);
            }
    
            protected override void OnPaint(PaintEventArgs pevent)
            {
                base.OnPaint(pevent);
                System.Windows.Forms.ControlPaint.DrawComboButton(pevent.Graphics, 0, 0, this.Width, this.Height, state);
            }
        }


       接下来再看下具有拉动功能的LABEL

      

    /// <summary>
        /// 重写LABEL
        /// </summary>
        public class LabelS : Label
        {
            public LabelS()
            {
                //控件绘制的时候减少闪烁
                this.SetStyle(ControlStyles.UserPaint, true);
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
                this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            }
    
            protected override void OnPaint(PaintEventArgs e)
            {
                base.OnPaint(e);
                System.Windows.Forms.ControlPaint.DrawSizeGrip(e.Graphics, Color.Black, 1, 0, this.Size.Width, this.Size.Height);
            }
        }


     接下来,我们动态用代码生成这些控件,并设置控件的布局,

     现在构造函数里生成这些控件,然后在用户控件的ComCheckBoxList_Layout事件里面布局这些控件,代码如下

      

     /// <summary>
        /// 带下拉框的用户控件
        /// </summary>
        public partial class ComCheckBoxList : UserControl
        {
            private TextBox tbSelectedValue;
            private ButtonS btnSelect;//下拉箭头
            private LabelS lbGrip;//此LABEL用于设置可以拖动下拉窗体变化
    
            private CheckedListBox checkListBox;
            private Label lbSelectAll;//全选
            private Label lbSelectNo;//取消
    
            private Form frmCheckList;
    
            private Panel pnlBack;
            private Panel pnlCheck;
    
            private System.Drawing.Point DragOffset; //用于记录窗体大小变化的位置
            public ComCheckBoxList()
            {
                InitializeComponent();
                this.Name = "comBoxCheckBoxList";
                this.Layout+=new LayoutEventHandler(ComCheckBoxList_Layout);
    
                //生成控件
                tbSelectedValue = new TextBox();
                tbSelectedValue.ReadOnly = true;
                tbSelectedValue.BorderStyle = BorderStyle.None;
    
                //下拉箭头
                this.btnSelect = new ButtonS();
                btnSelect.FlatStyle = FlatStyle.Flat;
                btnSelect.Click+=new EventHandler(btnSelect_Click);
    
                //全选
                this.lbSelectAll = new Label();
                lbSelectAll.BackColor = Color.Transparent;
                lbSelectAll.Text = "全选";
                lbSelectAll.Size = new Size(40, 20);
                lbSelectAll.ForeColor = Color.Blue;
                lbSelectAll.Cursor = Cursors.Hand ;
                lbSelectAll.TextAlign = ContentAlignment.MiddleCenter;
                lbSelectAll.Click+=new EventHandler(lbSelectAll_Click);
    
                //取消
                lbSelectNo = new Label();
                lbSelectNo.BackColor = Color.Transparent;
                lbSelectNo.Text = "取消";
                lbSelectNo.Size = new Size(40, 20);
                lbSelectNo.ForeColor = Color.Blue;
                lbSelectNo.Cursor = Cursors.Hand;
                lbSelectNo.TextAlign = ContentAlignment.MiddleCenter;
                lbSelectNo.Click+=new EventHandler(lbSelectNo_Click);
    
                //生成checkboxlist
                this.checkListBox = new CheckedListBox();
                checkListBox.BorderStyle = BorderStyle.None;
                checkListBox.Location = new Point(0,0);
                checkListBox.CheckOnClick = true;
                checkListBox.ScrollAlwaysVisible = true;
                checkListBox.LostFocus +=new EventHandler(checkListBox_LostFocus);
                checkListBox.ItemCheck+=new ItemCheckEventHandler(checkListBox_ItemCheck);
    
                //窗体
                frmCheckList = new Form();
                frmCheckList.FormBorderStyle = FormBorderStyle.None;
                frmCheckList.StartPosition = FormStartPosition.Manual;
                frmCheckList.BackColor = SystemColors.Control;
                frmCheckList.ShowInTaskbar = false;
    
                //可拖动窗体大小变化的LABEL
                lbGrip = new LabelS();
                lbGrip.Size = new Size(9,18);
                lbGrip.BackColor = Color.Transparent;
                lbGrip.Cursor = Cursors.SizeNWSE;
                lbGrip.MouseDown+=new MouseEventHandler(lbGrip_MouseDown);
                lbGrip.MouseMove+=new MouseEventHandler(lbGrip_MouseMove);
    
                //panel
                pnlBack = new Panel();
                pnlBack.BorderStyle = BorderStyle.Fixed3D;
                pnlBack.BackColor = Color.White;
                pnlBack.AutoScroll = false;
    
                //
                pnlCheck = new Panel();
                pnlCheck.BorderStyle = BorderStyle.FixedSingle;
                pnlCheck.BackColor = Color.White; ;
    
                SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
                SetStyle(ControlStyles.ResizeRedraw, true);
    
                pnlBack.Controls.Add(tbSelectedValue);
                pnlBack.Controls.Add(btnSelect);
    
                this.Controls.Add(pnlBack);
    
                pnlCheck.Controls.Add(checkListBox);
                pnlCheck.Controls.Add(lbSelectAll);
                pnlCheck.Controls.Add(lbSelectNo);
                pnlCheck.Controls.Add(lbGrip);
                this.frmCheckList.Controls.Add(pnlCheck);
    
              
            }
    
            private void ReloationGrip()
            {
    
                lbGrip.Top = this.frmCheckList.Height - lbGrip.Height - 1;
                lbGrip.Left = this.frmCheckList.Width - lbGrip.Width - 1;
    
                lbSelectAll.Left =5;
                lbSelectAll.Top = frmCheckList.Height - lbSelectAll.Height;
    
                lbSelectNo.Left = 50;
                lbSelectNo.Top = frmCheckList.Height - lbSelectNo.Height;
          
    
            }
    
            #region 事件
            
          
            //布局
            private void ComCheckBoxList_Layout(object sender,LayoutEventArgs e)
            {
                this.Height = tbSelectedValue.Height + 6;
                this.pnlBack.Size = new Size(this.Width, this.Height - 2);
    
                //设置按钮的位置
                this.btnSelect.Size = new Size(16, this.Height - 6);
                btnSelect.Location = new Point(this.Width - this.btnSelect.Width - 4, 0);
    
                this.tbSelectedValue.Location = new Point(2, 2);
                this.tbSelectedValue.Width = this.Width - btnSelect.Width - 4;
    
                checkListBox.Height =150;
    
                //设置窗体
                this.frmCheckList.Size = new Size(this.Width,this.checkListBox.Height);
                this.pnlCheck.Size =frmCheckList.Size;
               
    
                this.checkListBox.Width = this.frmCheckList.Width;
                this.checkListBox.Height = this.frmCheckList.Height-lbSelectNo.Height;
    
                ReloationGrip();
    
    
            }
            /// <summary>
            /// 单价下拉框
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void btnSelect_Click(object sender,EventArgs e)
            {
                if (this.frmCheckList.Visible == false)
                {
                    Rectangle rec = this.RectangleToScreen(this.ClientRectangle);
                    this.frmCheckList.Location = new Point(rec.X, rec.Y + this.pnlBack.Height);
                    this.frmCheckList.Show();
                    this.frmCheckList.BringToFront();
    
                    ReloationGrip();
                }
                else
                    this.frmCheckList.Hide();
            }
    
            //全选事件
            private void lbSelectAll_Click(object sender, EventArgs e)
            { 
            
            }
            //取消
            private void lbSelectNo_Click(object sender,EventArgs e)
            { 
            
            }
    
            private void checkListBox_LostFocus(object sender, EventArgs e)
            {
                //如果鼠标位置在下拉框按钮的以为地方,则隐藏下拉框
                if (!this.btnSelect.RectangleToScreen(this.btnSelect.ClientRectangle).Contains(Cursor.Position))
                {
                    frmCheckList.Hide();
                }
            }
    
            private void checkListBox_ItemCheck(object sender, ItemCheckEventArgs e)
            {
    
            }
    
            /// <summary>
            /// 鼠标按下
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void lbGrip_MouseDown(object sender, MouseEventArgs e)
            {
                if (e.Button==MouseButtons.Left)
                {
                    int offsetX = System.Math.Abs(Cursor.Position.X - frmCheckList.RectangleToScreen(this.frmCheckList.ClientRectangle).Right);
                    int offsetY = System.Math.Abs(Cursor.Position.Y - frmCheckList.RectangleToScreen(this.frmCheckList.ClientRectangle).Bottom);
                    this.DragOffset = new Point(offsetX, offsetY);
                }
            }
    
            /// <summary>
            /// 鼠标移动
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void lbGrip_MouseMove(object sender,MouseEventArgs e)
            {
                if (e.Button==MouseButtons.Left)
                {
                    //获取拉伸长度
                    int curWidth = Cursor.Position.X - frmCheckList.Location.X;
                    int curHeight = Cursor.Position.Y - frmCheckList.Location.Y;
                      if (curWidth<this.Width)
    	              {
    		                curWidth=this.Width;
    	               }
    
                      if (curHeight<checkListBox.Height)
    	              {
    		                curHeight=checkListBox.Height;
    	              }
              
                    this.frmCheckList.Size=new Size(this.Width,curHeight);
                    this.pnlCheck.Size=frmCheckList.Size;
                    this.checkListBox.Height=(this.frmCheckList.Height-lbGrip.Height)<50?50:this.frmCheckList.Height-lbGrip.Height;
    
                   ReloationGrip();
                    SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
                    SetStyle(ControlStyles.ResizeRedraw, true);
                    SetStyle(ControlStyles.UserPaint, true);
                    SetStyle(ControlStyles.AllPaintingInWmPaint, true);
                    
    
    
                }
            }
    
            #endregion
        }


      这样用户控件的布局以及完成,我们编译项目,就可以拖动用户控件到窗体上,看到效果了

     

    2. 绑定和添加数据

            2.1 从数据库中读取数据绑定显示

                   既然可以从数据库中读取数据,数据源就可以是DATATABLE,我们在这里为用户控件设置数据源,以及绑定后,要显示的字段,以及对于的值字段。

                  为控件添加以下属性

                

        /// <summary>
            /// 设置数据源
            /// </summary>
            public object DataSource
            {
                set
                {
                    this.checkListBox.DataSource = value;
                }
                get
                {
                    return checkListBox.DataSource;
                }
            }
            /// <summary>
            /// 设置值
            /// </summary>
            public string ValueMember
            {
                set
                {
                    checkListBox.ValueMember = value;
                }
            }
            /// <summary>
            /// 设置显示名称
            /// </summary>
            public string DisplayMember
            {
                set
                {
                    checkListBox.DisplayMember = value;
                }
            }


              2.2 添加项

               我们也可以不绑定数据源,为控件添加项,所有这里我们要为控件添加一个方法,可以实现手动添加项。

               

      /// <summary>
            /// 添加项
            /// </summary>
            public int AddItems(object value)
            {
                checkListBox.Items.Add(value);
                return checkListBox.Items.Count;
            }


        这样我们就为用户控件实现了两种显示数据的方法。下面我们看看在窗体中怎样使用这两种方法

         在窗体上放置两个按钮,然后绑定数据

       

     private void button1_Click(object sender, EventArgs e)
            {
                //绑定数据源
                DataTable dt = new DataTable();
                DataColumn dc1 = new DataColumn("weibo", typeof(System.String));
                dt.Columns.Add(dc1);
    
                DataColumn dc2 = new DataColumn("mail", typeof(System.String));
                dt.Columns.Add(dc2);
    
                DataColumn dc3 = new DataColumn("blog", typeof(System.String));
                dt.Columns.Add(dc3);
    
    
                for (int i = 0; i < 50; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = "下里巴人simple";
                    dr[1] = "524300045@qq.com";
                    dr[2] = "msdn" + i.ToString();
                    dt.Rows.Add(dr);
                }
                comCheckBoxList1.DataSource = dt;
                comCheckBoxList1.DisplayMember = "weibo";
                comCheckBoxList1.ValueMember = "mail";
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                //添加项
                comCheckBoxList2.AddItems("邮箱:524300045@qq.com");
                comCheckBoxList2.AddItems("微博:下里巴人simple");
            }

      至此,第二步骤已经完成,可以实现大部分功能了.

       3.事件处理

         这里我们定义下全选事件,取消事件,和某项选中状态更改时发生的事件

       

      //全选事件
            private void lbSelectAll_Click(object sender, EventArgs e)
            {
                for (int i = 0; i < checkListBox.Items.Count; i++)
                {
                    checkListBox.SetItemChecked(i, true);
                }
                tbSelectedValue.Text ="已选择"+checkListBox.Items.Count.ToString()+"项";
            }
            //取消
            private void lbSelectNo_Click(object sender,EventArgs e)
            {
                for (int i = 0; i < checkListBox.Items.Count; i++)
                {
                    checkListBox.SetItemChecked(i, false);
                }
                tbSelectedValue.Text = "没有选择!";
            }


         这里我们自定义一个选项状态更改时发生的事件,供别人使用的时候自行处理选择状态更改逻辑,需要我们自定义事件

      

      //单击列表项状态更改事件
            public delegate void CheckBoxListItemClick(object sender, ItemCheckEventArgs e);
            public event CheckBoxListItemClick ItemClick;

       

       private void checkListBox_ItemCheck(object sender, ItemCheckEventArgs e)
            {
                ItemClick(sender, e);
    
               //获取选中的数量
                int nCount = this.checkListBox.CheckedItems.Count;
                if (this.checkListBox.CheckedItems.Contains(this.checkListBox.Items[e.Index]))
                {
    
                    if (e.NewValue != CheckState.Checked)
                    {
                        nCount--;
                    }
                }
                else
                {
                    if (e.NewValue == CheckState.Checked)
                    {
                        nCount++;
                    }
                }
                tbSelectedValue.Text = "已选择" + nCount.ToString() + "项";
           
            }

      

      /// <summary>
            /// 选项集合
            /// </summary>
            public CheckedListBox.ObjectCollection Items
            {
                get
                {
                    return checkListBox.Items;
                }
            }
    
            /// <summary>
            /// 获取选中项的文本
            /// </summary>
            /// <param name="item"></param>
            /// <returns></returns>
            public string GetItemText(object item)
            {
                return checkListBox.GetItemText(item);
            }


     

    然后当用户把控件拖放到窗体上,我们就可以使用该事件了。

      

      /// <summary>
            /// 获取选中项的文本
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void comCheckBoxList1_ItemClick(object sender, ItemCheckEventArgs e)
            {
              string text=comCheckBoxList1.GetItemText(comCheckBoxList1.Items[e.Index]);
              MessageBox.Show(text);
            }


        到此,这个控件的基本功能已经实现完成。再看下效果图

               

         demo下载:http://download.csdn.net/detail/zx13525079024/4454696

    展开全文
  • 在实际工作中,如果能像菜单一样弹出自定义内容,会方便很多,比如查询时,比如下拉列表显示多列信息时,比如在填写某个信息需要查看一些信息树时。这个时候自定义弹出界面就显的非常重要了 我这里其实用到的是网上...
  • 需求:要求datagridview同一列,每一行显示不同的下拉表内容来提供选择列表项。另外没有下拉内容的行需要支持可输入可编辑。 然而,datagridview 自带的DatagridviewcomboboxColumn 默认的下拉样式为dropdownlist,...
  • Demo包含一些自定义控件(下拉列表,树形列表 , 图片列表等)均可实现透明效果。主窗体是一个海康相机的监控视频。使用时可替换成其他视频。
  • ComboBox 下拉列表框 Checkbox 复选框 RadioButton 单选框 GroupBox 分组控件 Label 标签 ListBox 列表框 PictureBox 图片框 DateTimePicker 日期时间控件 ProgressBar 进度条 NumericUpDown 数字输入框 ...
  • ,设置第一列列为下拉列表,另一列根据第一列选择的结果,决定...举例第一列里面选择项有日期和自定义,选择日期,另一列就是下拉列表,里面数据是日期格式的选择,选择自定义,另一列就是可编辑的文本框,可以自由输入
  • WinForm下,用DEV的GridControl控件,其中某一列(列1)设置为下拉列表,有三个选项,日期,自定义,流水号,另一列(列2)也是下拉列表,根据列1选择不同会出现不同内容,在列1选择完列2就加载,并显示一个默认值...
  • Winform智能提示效果

    2012-03-14 11:02:59
    最可能的匹配项自动追加到当前数据并产生由一个或多个建议完成字符串组成的下拉列表。 AutoCompleteSource属性允许您从一些系统源中进行选择,例如 FileSystem、HistoryList、RecentlyUsedList、AllUrl 和 Custom...
  • 在实际工作中,如果能像菜单一样弹出自定义内容,会方便很多,比如查询时,比如下拉列表显示多列信息时,比如在填写某个信息需要查看一些信息树时。这个时候自定义弹出界面就显的非常重要了
  • 原文:Winform 实现像菜单一样弹出层在实际工作中,如果能像菜单一样弹出自定义内容,会方便很多,比如查询时,比如下拉列表显示多列信息时,比如在填写某个信息需要查看一些信息树时。这个时候自定义弹出界面就显...
  • C#Winform工具箱简介

    2019-03-24 04:52:00
    BindingSource:指定支持事务处理初始化Button:【按钮】用户单击它时...ColorDialog:【颜色对话框】显示可用的颜色以及允许用户定义自定义颜色的控件ComboBox:【组合框(下拉对话框) 】显示一个可编辑的文本框,...
  • ③,在下拉列表中可显示自定义的多列数据。④,可在下拉列表中通过输入关键字,自动搜索符合条件的数据行。⑤,可指定不同的值列和显示列。⑥,可设置是否显示行头和列头。⑦,程序根据显示列的多少和宽度,自动调整...
  • ImageComboBoxItem类实现了ISerializable接口,实现自定义序列化。ImageComboBoxItem类的类视图如下: 图3 ImageComboxItem类视图 ImageComboBoxItem类的代码如下: [Serializable] [DefaultProperty...
  • Skill&Buff Editor

    2020-04-02 10:57:25
    之前项目做的一个moba的skill&...节点的属性编辑(图中右上角)通过扩展winform的profertygrid,实现了包括下拉选择、下拉多选、自定义列表自定义类字典等多种格式编辑(如图中右下角为点击“...
  • 用户控件的随想

    2009-12-21 14:06:00
    最近在鼓弄winform的combobox控件发觉还真的学到好多的呢 幸福ing~~~~很多时候如果我们...会方便n百倍下面贴下的我东东 一个实现可调整comboBox的下拉列表的大小的控件1、项目添加用户自定义控件 取名CtrlComboBox 拖拽
  • 如何为DataGrid添加下拉列表框.txt 如何用C#在Excel中生成图表?.txt 如何用程序实现键盘和鼠标的模拟?.txt 如何与资源管理器互动剪切、拷贝、粘贴文件.txt 深入理解C#编程中的组件-事件-委托.txt 生成透明的...

空空如也

空空如也

1 2
收藏数 39
精华内容 15
关键字:

winform自定义下拉列表