我在 WindowsForms 中有一个组合框,我手动绘制项目。每个项目都由图片和文本(Cell.Image 和 Cell.Title)组成,因此项目高度为 34 px。
我的问题是,当我下拉 ComboBox 时,只有 1 个项目可见。 MaxDropDownItems = 4 因此 ComboBox 将绘制 4 个项目。我知道我已经设置了 DropDownHeight = 34,但我想在 ComboBox 中没有项目时显示空矩形,如下图所示。
没有项目的组合框 - 好的:
只有 1 个可见项目的组合框 - 不好:
我的类派生自 ComboBox:
public class ComboBoxCells : ComboBox
{
private List<Cell> _cells;
public List<Cell> Cells
{
get { return this._cells; }
set
{
this._cells = value;
this.BeginUpdate();
this.Items.Clear();
if (value != null)
this.Items.AddRange(value.ToArray());
this.EndUpdate();
}
}
public ComboBoxCells()
{
this.DrawMode = DrawMode.OwnerDrawVariable;
this.DropDownHeight = 34;
this.DropDownWidth = 200;
this.DropDownStyle = ComboBoxStyle.DropDownList;
this.MaxDropDownItems = 4;
this.DrawItem += new DrawItemEventHandler(ComboBoxCells_DrawItem);
this.MeasureItem += new MeasureItemEventHandler(ComboBoxCells_MeasureItem);
}
private void ComboBoxCells_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
// Draw item inside comboBox
if ((e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit && e.Index > -1)
{
Cell item = this.Items[e.Index] as Cell;
e.Graphics.FillRectangle(Brushes.Gray, new Rectangle(e.Bounds.Left + 6, e.Bounds.Top + 6, 22, 22));
e.Graphics.DrawImage(item.Image, new Rectangle(e.Bounds.Left + 7, e.Bounds.Top + 7, 20, 20));
e.Graphics.DrawString(item.Title, e.Font,
new SolidBrush(e.ForeColor), e.Bounds.Left + 34, e.Bounds.Top + 10);
}
// Draw visible text
else if (e.Index > -1)
{
Cell item = this.Items[e.Index] as Cell;
e.Graphics.DrawString(item.Title, e.Font,
new SolidBrush(e.ForeColor), e.Bounds.Left, e.Bounds.Top);
}
e.DrawFocusRectangle();
}
private void ComboBoxCells_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 34;
}
}
谢谢
最佳答案
DropDownHeight 是您想要设置更高的数字。它是下拉框的最大像素数。系统会自动将其设为您的元素高度的最大倍数。
this.DropDownHeight = 200;
关于c# - 在 ComboBox 中绘制图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5677117/