在设计师中创建一个固定高度的自定义控件。

6

我希望创建一个自定义控件(派生于Control类),当我将这个自定义控件拖到设计器中的表单时,我只能更改它的宽度。这个特性和单行文本框相同。

更新:我的应用程序是Windows Form。

3个回答

16

请查看http://www.windowsdevelop.com/windows-forms-general/how-to-set-that-a-control-resizes-in-width-only-9207.shtml

你可以重写SetBoundsCore方法并定义一个设计器来删除控件的上下调整大小手柄。

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace MyControlProject
{
    [Designer(typeof(MyControlDesigner))]
    public class MyControl : Control
    {
        protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
        {
            height = 50;
            base.SetBoundsCore(x, y, width, height, specified);
        }
    }

    internal class MyControlDesigner : ControlDesigner
    {
        MyControlDesigner()
        {
            base.AutoResizeHandles = true;
        }
        public override SelectionRules SelectionRules
        {
            get
            {
                return SelectionRules.LeftSizeable | SelectionRules.RightSizeable | SelectionRules.Moveable;
            }
        }
    }
}

链接已经失效了。我是否缺少引用?我已经包含了相关文件,但是它仍然找不到我要继承的ControlDesigner类。这个类可用的最低.NET Framework版本是多少? - Matheus Rocha
Matheus:你必须在项目中手动添加System.Design作为引用。 - BenW

9

对我也起作用。被接受的答案中的链接似乎已经下线,所以很高兴我们有这个答案。 - xsl
1
请记得将“指定”设置为您的覆盖更改的维度。 在此示例中,您强制定义高度,因此“指定”应为“BoundsSpecified.Height”。就像这样:base.SetBoundsCore(x, y, width, 75, BoundsSpecified.Height);来源:MSDN文档 - Matheus Rocha

1
    this.MaximumSize = new System.Drawing.Size(0, 20);
    this.MinimumSize = new System.Drawing.Size(0, 20);

显然,.NET假定最小宽度和最大宽度为0时为"任意宽度"。


我通常会在回答问题之前尝试重现它,但这已经是一年前的事了;我不记得回答过这个问题,所以也许你应该直接看一下被接受的答案。 - C.Evenhuis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接