ste*_*nar 3

我能够在 15 分钟内完成以下操作,所以是的。主要思想是处理 DrawItem 事件。

\n\n

以下是我对这个问题的看法(您可以看到另一个示例,在此处的项目中绘制图标)。

\n\n
public partial class Form1 : Form  \n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        this.comboBox1.DrawMode = DrawMode.OwnerDrawVariable;            \n        this.comboBox1.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem);\n        this.comboBox1.Items.Add("Some text that needs to be take up two lines...");\n        this.comboBox1.ItemHeight = 30;\n    }\n\n    IEnumerable<string> WrapString(string str, Graphics g, Font font, \n                                   int allowedWidth)\n    {            \n        string[] arr = str.Split(\' \');            \n        StringBuilder current = new StringBuilder();\n        foreach (string token in arr)\n        {                \n            // TODO: You\'ll have to fix this, might break in marginal cases\n            int width = \n              (int)g.MeasureString(current.ToString() + " " + token, font).Width;\n            if (width > allowedWidth)\n            {\n                yield return current.ToString();\n                current.Clear();\n            }\n\n            current.Append(token + " ");\n\n        }\n        yield return current.ToString();\n    }\n\n    void comboBox1_DrawItem(object sender, DrawItemEventArgs e)\n    {\n        Brush backgroundBrush, forgroundBrush;\n\n        if (e.State == (DrawItemState.Selected | \n                    DrawItemState.NoAccelerator | DrawItemState.NoFocusRect) ||\n            e.State == DrawItemState.Selected) \n        {\n            forgroundBrush = Brushes.Black;\n            backgroundBrush = Brushes.White;\n        }\n        else\n        {\n            forgroundBrush = Brushes.White;\n            backgroundBrush = Brushes.Black;\n        }\n\n        // some way to wrap the string (on a space)           \n        string str = (string)comboBox1.Items[e.Index];\n\n\n        Rectangle rc = \n           new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);\n        e.Graphics.FillRectangle(forgroundBrush, rc);\n\n        int stringHeight = \n               (int)e.Graphics.MeasureString(str, comboBox1.Font).Height;\n        int lineNo = 0;\n        foreach (string line in \n                      WrapString(str, e.Graphics, comboBox1.Font, e.Bounds.Width))\n        {\n            e.Graphics.DrawString(line, comboBox1.Font, backgroundBrush, \n                                  new PointF(0, lineNo * stringHeight + 5));\n            lineNo++;\n        }            \n    }             \n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

用法:创建一个常规表单并在其上放置一个组合框。

\n\n

(请注意,这当然只是一个 na\xc3\xafve 概念证明 - 显然还有改进的空间。而且它只是假设只有两行而不是一行。但它表明这是可能的。)

\n