【问题标题】:Set UserControl's max height without setting max width设置 UserControl 的最大高度而不设置最大宽度
【发布时间】:2017-10-29 20:23:04
【问题描述】:

我有一个带有预定义值的组合框的用户控件。我认为使用此控件的程序员将能够水平拉伸控件,但不能垂直拉伸。

Here, @SLaks 建议设置MaximumSize 属性,但是,我必须限制宽度,我不想这样做。

那么如何实现呢?

【问题讨论】:

  • 为什么不将MaximumSize 设置为(int.MaxValue, Height)
  • 从 ComboBox 派生您自己的类几乎总是一个更好的主意。您将继承其所有默认行为,包括调整大小的方式。只有在需要组合多个控件时才使用 UserControl。

标签: c# .net winforms user-controls windows-forms-designer


【解决方案1】:

您可以覆盖SetBoundsCore 并使其使用ComboBox 的高度作为控件的高度:

protected override void SetBoundsCore(int x, int y, int width, int height,
    BoundsSpecified specified)
{
    base.SetBoundsCore(x, y, width, comboBox1.Height, specified);
}

注意 1:如果您的 UserControl 仅包含 ComboBox,则最好从 ComboBox 派生而不是创建包含 ComboBox 的用户控件

注意 2: 您可以通过创建新的 ControlDesigner 并覆盖 SelectionRules 属性,在设计器中明确控制可以从左侧或右侧调整大小。为此,请添加对 System.Design 程序集的引用,然后创建自定义设计器:

using System.Windows.Forms.Design;
public class MyControlDesigner : ControlDesigner
{
    public override SelectionRules SelectionRules
    {
        get
        {
            return SelectionRules.LeftSizeable |
                   SelectionRules.RightSizeable |
                   SelectionRules.Moveable;
        }
    }
}

那么用设计器属性来装饰你的自定义控件就足够了:

[Designer(typeof(MyControlDesigner))]

【讨论】:

  • 如果您对这篇文章有任何疑问,请告诉我。这是创建固定高度控件的最佳解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 2021-06-21
  • 1970-01-01
  • 2023-03-23
  • 2016-03-30
  • 2018-11-08
  • 1970-01-01
相关资源
最近更新 更多