设置复选框的高度不起作用

Set height of check list box not working

我正在使用 C#,Visual Studio Express 2013。 我有 CheckListBox,根据基础数据,我可以在其中包含不同数量的项目。我正在尝试根据项目数调整 CheckListBox 的高度。 目前,一旦填充了项目列表,我就会调用以下方法来设置 CheckListBox 的高度:

        private void SetPanelSize()
        {
            int top = tbInstructions.Height + 2;
            int optionsHeight = 0;

            for (int i = 0; i < cbOptions.Items.Count; i++)
            {
                optionsHeight += cbOptions.GetItemHeight(i);
            }

            cbOptions.Location = new Point(4, top);
            cbOptions.Height = optionsHeight;
        }

当我运行此程序时,CheckListBox 高度设置为比项目数少一项 - 即,如果有三个项目,则只有两个可见,需要向下滚动才能看到第三个。 在调试之后,每个选项高度返回为 16。在三个项目的情况下,这给出 optionsHeight 为 48。但是当分配 cbOptions.Height 设置为 36.

我在之前计算高度的方法中看到过这一点 - 当我将它分配给高度时,我计算的值发生了变化。 到底是怎么回事?我错过了什么吗?我在我看过的文献(主要是 MSDN)中找不到关于调整高度分配的参考。

非常感谢任何帮助。

CheckListBox 本身需要一定的高度。所以需要给CheckListBox的高度加上optionsHeight。尝试以下代码,它会起作用:

cbOptions.Height += optionsHeight;

确保将 IntegralHeight 属性 设置为 false,并且还必须补偿边框大小:

cbOptions.IntegralHeight = false;
int optionsHeight = 0;
if (cbOptions.BorderStyle == BorderStyle.Fixed3D) {
  optionsHeight = SystemInformation.Border3DSize.Height * 2;
} else if (cbOptions.BorderStyle == BorderStyle.FixedSingle) {
  optionsHeight = SystemInformation.BorderSize.Height * 2;
}