在设计器中创建一个具有固定高度的自定义控件

时间:2010-04-06 05:00:32

标签: c# .net winforms designer

我想创建一个自定义控件(从Control类派生),当我将此自定义控件拖到设计器中的表单时,我只能更改其宽度。此功能与单行文本框相同。

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

3 个答案:

答案 0 :(得分:10)

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

重写SetBoundsCore并定义Designer以删除顶部和底部调整大小手柄。

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;
            }
        }
    }
}

答案 1 :(得分:8)

试试这个

protected override void SetBoundsCore(int x, int y, 
   int width, int height, BoundsSpecified specified)
{
   // Set a fixed height for the control.
   base.SetBoundsCore(x, y, width, 75, specified);
}

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.setboundscore(VS.71).aspx

答案 2 :(得分:1)

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

显然.NET假定最小和最大宽度为0为“任何宽度”。