简体   繁体   English

我无法将 ComboBox 停靠在 TableLayoutPanel 单元格中

[英]I am unable to dock a ComboBox in a TableLayoutPanel cell

Please see the image below: I want to dock a ComboxBox control in a cell of my TableLayoutPanel.请看下图: 我想在我的 TableLayoutPanel 的单元格中停靠一个ComboxBox控件。

The ComboBox Dock property is set to Fill and the Anchor property to top, bottom, left and right . ComboBox Dock属性设置为FillAnchor属性设置为top、bottom、left 和 right

显示的属性和文档大纲也显示在表单中

As suggested already you cannot change the height of combobox and textbox using anchor or dock property.正如已经建议的那样,您不能使用锚点或停靠属性更改 combobox 和文本框的高度。 You can change the font size in Font property.您可以在 Font 属性中更改字体大小。 the default is 8.25pt.默认值为 8.25pt。

Like Here像这儿

TL; TL; DR博士

It's expected behavior, for ComboBox setting Dock to Fill doesn't fill the container.这是预期的行为,对于ComboBoxDock设置为Fill不会填充容器。 it's Height is calculated based on its Font height or for an owner-draw ComboBox based on its ItemHeight .它的高度是根据其Font高度计算的,或者对于所有者绘制的 ComboBox 根据其ItemHeight

If it's really necessary for you to change the behavior, you can hack the behavior by overriding its SetBoundsCore method.如果您确实需要更改行为,您可以通过覆盖其SetBoundsCore方法来破解该行为。


Long Answer - A ComboBox which supports Dock = Fill长答案 - 支持 Dock = Fill 的 ComboBox

The height of ComboBox is controlled based on the following rules: ComboBox的高度根据以下规则控制:

  • If the control's DrawMode is Normal, then the height will be based on Font.Height如果控件的DrawMode为 Normal,则高度将基于 Font.Height
  • If the control's DrawMode is OwnerDraw then the height will be based on the ItemHeight如果控件的DrawMode是 OwnerDraw 那么高度将基于ItemHeight

So it doesn't support Docking-Fill.所以它不支持对接填充。

But you can hack the behavior;但是你可以破解这种行为; You can derive from ComboBox and change the behavior by overriding SetBoundsCore :您可以从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);
    }
}

And as result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM