带有checkList的comboBox

时间:2011-02-07 07:41:45

标签: c# combobox

如何在C#中使用带有checkList的comboBox?

2 个答案:

答案 0 :(得分:1)

我自己一直在搞乱这件事。这是一个控件的小样本,其中包含真正的CheckBox,而不仅仅是绘制它们。这样您就可以真正使用CheckBox类提供的所有功能。它取代了ComboBox的常规下拉,其中包含一个继承ToolStripDropDownMenu的自定义下拉菜单,它允许您向其添加实际控件,并解决每次单击项目时关闭下拉的问题。您显然希望扩展MyComboBox类以满足您的需求,但它应该是一个很好的起点。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        var mcb = new MyComboBox() { Left = 6, Top = 6 };
        this.Controls.Add(mcb);

        for (int i = 0; i < 20; i++)
        {
            mcb.AddItem("Item " + i.ToString() );
        }
    }
}

public class MyComboBox : ComboBox
{
    private MyDropDown _dropDown;

    public MyComboBox()
    {
        _dropDown = new MyDropDown() { Width = 200, Height = 200 };
    }

    public void AddItem(string text)
    {
        _dropDown.AddControl(new CheckBox() { Text = text });
    }

    public void ShowDropDown()
    {
        if (_dropDown != null)
        {
            _dropDown.Show(this);
        }
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WndUI.WM_REFLECT + WndUI.WM_COMMAND)
        {
            if (WndUI.HIWORD(m.WParam) == WndUI.CBN_DROPDOWN)
            {
                ShowDropDown();
                return;
            }
        }
        base.WndProc(ref m);
    }
}

[ToolboxItem(false)]
public class MyDropDown : ToolStripDropDownMenu
{
    public MyDropDown()
    {
        this.ShowImageMargin = this.ShowCheckMargin = false;
        this.AutoSize = false;
        this.DoubleBuffered = true;
        this.Padding = Margin = Padding.Empty;
    }

    public int AddControl(Control control)
    {
        var host = new ToolStripControlHost(control);
        host.Padding = host.Margin = Padding.Empty;
        host.BackColor = Color.Transparent;
        return this.Items.Add(host);
    }

    public void Show(Control control)
    {
        Rectangle area = control.ClientRectangle;
        Point location = control.PointToScreen(new Point(area.Left, area.Top + area.Height));
        location = control.PointToClient(location);
        Show(control, location, ToolStripDropDownDirection.BelowRight);
        this.Focus();
    }
}

public static class WndUI
{
    public const int
        WM_USER = 0x0400,
        WM_REFLECT = WM_USER + 0x1C00,
        WM_COMMAND = 0x0111,
        CBN_DROPDOWN = 7;

    public static int HIWORD(IntPtr n)
    {
        return HIWORD(unchecked((int)(long)n));
    }

    public static int HIWORD(int n)
    {
        return (n >> 16) & 0xffff;
    }
}

答案 1 :(得分:0)

编辑:我认为这更合适:http://www.codeproject.com/KB/combobox/CheckComboBox.aspx

我找到了这个链接:http://www.codeproject.com/KB/combobox/extending_combobox.aspx希望它有所帮助。