如何使UserControl锁定到一定的高度?

时间:2011-12-01 21:10:12

标签: winforms user-controls

不允许用户垂直调整TextBox控件的大小。 TextBox的高度锁定到文本框应该是理想的高度。

更重要的是,Visual Studio甚至没有为您提供垂直拖动句柄:

enter image description here

如何在UserControl上提供相同的机制?

1 个答案:

答案 0 :(得分:6)

我将详细阐述汉斯的评论。您可以将专用代码(称为Designer)与UserControl相关联,以便在将其放置在Visual Studio中的表单上时,用户在配置控件时的方式受到限制。

  1. 在项目中添加对System.Design的引用。

  2. 使用以下示例代码:

    [Designer(typeof(FixedHeightUserControlDesigner))]
    public partial class FixedHeightUserControl : UserControl
    {
        private const int FIXED_HEIGHT = 25;
    
        protected override void OnSizeChanged(EventArgs e)
        {
            if (this.Size.Height != FIXED_HEIGHT)
                this.Size = new Size(this.Size.Width, FIXED_HEIGHT);
    
            base.OnSizeChanged(e);
        }
    
        public FixedHeightUserControl()
        {
            InitializeComponent();
    
            this.Height = FIXED_HEIGHT;
        }
    }
    
    public class FixedHeightUserControlDesigner : ParentControlDesigner
    {
        private static string[] _propsToRemove = new string[] { "Height", "Size" };
    
        public override SelectionRules SelectionRules
        {
            get { return SelectionRules.LeftSizeable | SelectionRules.RightSizeable | SelectionRules.Moveable; }
        }
    
        protected override void PreFilterProperties(System.Collections.IDictionary properties)
        {
            base.PreFilterProperties(properties);
            foreach (string p in _propsToRemove)
                if (properties.Contains(p))
                    properties.Remove(p);
        }
    }