Winform ComboBox 下拉列表多显示

参考于

https://www.cnblogs.com/axing/archive/2013/06/07/3123123.html

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestA
{
public partial class ComboBox 1: ComboBox
{
#region 属性设置
///


/// 鼠标移动上的背景颜色
///

public Color MouseOverBackground { get; set; } = Color.Gray;
///
/// 鼠标移动上的字体颜色
///

public Color MouseOverForeground { get; set; } = Color.Orange;
///
/// 边框颜色
///

public Color BorderBrush { get; set; } = Color.Black;
///
/// 边框大小
///

public int BorderSize { get; set; } = 0;
///
/// 单元格大小
///

public int ColumnWidth { get; set; } = 100;
#endregion
private int OldItemHeight = 0;//用于记录加载时的ItemHeight

    public ComboBoxOne()
    {
        InitializeComponent();
        DrawMode = DrawMode.OwnerDrawFixed;
    }
    protected override void OnDropDown(EventArgs e)
    {
        DropDownWidth = (DataManager.Count - 1) * ColumnWidth;//根据字段数量与每个字段的长度进行设置最大长度
        OldItemHeight = ItemHeight;//保存加载时的Item高度
        ItemHeight = 24;//Item高度变高 不然居中就出界了
        base.OnDropDown(e);
    }
    protected override void OnDropDownClosed(EventArgs e)
    {
        ItemHeight = OldItemHeight;//将高度变回去
        base.OnDropDownClosed(e);
    }
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        var a = DrawItemState.Selected | DrawItemState.Default;
        Bitmap map = new Bitmap(DropDownWidth, ItemHeight);
        Graphics g = Graphics.FromImage(map);
        Pen BorderPen = new Pen(BorderBrush, BorderSize);//边框画笔
        e.Graphics.FillRectangle(new SolidBrush(BackColor), e.Bounds);//正常背景
        if (e.State.ToString().IndexOf(DrawItemState.Selected.ToString())!=-1)//选中背景
        {
            e.Graphics.FillRectangle(new SolidBrush(MouseOverBackground), e.Bounds);
        }
        if (BorderSize > 0)//因为即使BorderSize也会画出来 所以直接判断
            e.Graphics.DrawRectangle(BorderPen, e.Bounds);//绘制边框
        PropertyDescriptorCollection ps = DataManager.GetItemProperties();//所有的标题/列名
        for (int f = 0; f < ps.Count; f++)
        {
            Font ValueMemberFont = new Font("", Font.Size + 2);//Value的字体
            ValueMemberFont = new Font(ValueMemberFont, FontStyle.Underline);
            String column = FilterItemOnProperty(Items[e.Index], ps[f].DisplayName).ToString();//获取一个这个位置的字段
            e.Graphics.DrawString(column, f == 0 ? ValueMemberFont : Font, e.State == DrawItemState.Selected ? new SolidBrush(MouseOverForeground) : new SolidBrush(ForeColor), f * ColumnWidth, e.Bounds.Y + Font.Size / 2);//尝试绘制一个上下居中文本
            if (BorderSize > 0)
                e.Graphics.DrawLine(BorderPen, ColumnWidth * (f + 1), 0, ColumnWidth * (f + 1), ItemHeight * Items.Count);//竖线
        }
        base.OnDrawItem(e);
    }
}

}

上一篇:textbox根据combobox的值确定能否修改


下一篇:CodeGo.net>如何使用组合框将新项目添加到数据源?