问题描述
请参见下图:我想在 TableLayoutPanel 的单元格中停靠 ComBoxBox 控件。
ComboBox Dock
属性设置为Fill,Anchor
属性设置为顶部、底部、左侧和右侧。
解决方法
正如已经建议的那样,您不能使用锚点或停靠点属性更改组合框和文本框的高度。您可以在 Font 属性中更改字体大小。默认值为 8.25pt。
,TL;博士
这是预期的行为,因为 ComboBox
将 Dock
设置为 Fill
不会填满容器。它的高度是根据它的 Font
高度计算的,或者是基于它的 ItemHeight
的所有者绘制的 ComboBox。
如果您确实有必要更改行为,您可以通过覆盖其 SetBoundsCore
方法来破解该行为。
长答案 - 支持 Dock = Fill 的 ComboBox
ComboBox
的高度根据以下规则控制:
- 如果控件的
DrawMode
为 Normal,则高度将基于 Font.Height - 如果控件的
DrawMode
是 OwnerDraw,那么高度将基于 ItemHeight
所以它不支持Docking-Fill。
但是你可以破解这个行为;您可以从 ComboBox
派生并通过覆盖 SetBoundsCore
来更改行为:
using System.Windows.Forms;
public class MyComboBox : ComboBox
{
public MyComboBox()
{
DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void SetBoundsCore(
int x,int y,int width,int height,BoundsSpecified specified)
{
base.SetBoundsCore(x,y,width,height,specified);
if (Dock == DockStyle.Fill ||
Dock == DockStyle.Left ||
Dock == DockStyle.Right)
{
var d = SystemInformation.FixedFrameBorderSize.Height;
ItemHeight = height - 2 * d;
}
else
{
ItemHeight = FontHeight + 2;
}
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
var text = e.Index >= 0 ? GetItemText(e.Index) : string.Empty;
TextRenderer.DrawText(e.Graphics,text,e.Font,e.Bounds,e.ForeColor,TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
base.OnDrawItem(e);
}
}
结果: