Getting initial dimensions from an inherited UserControl

I am trying to create a series of UserControls that all inherit from a custom UserControl object. One of the key points I want to implement is the ability to dynamically resize all controls to fit the size of the control.

To do this, I need to get the initial width and height of the control in order to compare it to the dimensions. In my inherited controls, I can put the code in the constructor after calling InitializeComponent () to grab the dimensions. Is there a way to do this from basic object code?

Also, if there is a better approach to this, I am open to suggestions.

+2


source to share


2 answers


As a result, I used the control's base dimensions as the fixed size for all inherited controls. It was pretty easy to do this by overriding the SetBoundsCore () method:

public partial class BaseControl : UserControl
{
    private int _defaultWidth;
    private int _defaultHeight;

    public BaseControl()
    {
        InitializeComponent();

        _defaultWidth = this.Width;
        _defaultHeight = this.Height;
    }        

    protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
    {
        if (this.DesignMode)
        {
            width = _defaultWidth;
            height = _defaultHeight;
        }

        base.SetBoundsCore(x, y, width, height, specified);
    }
}    

      



Any controls inherited from BaseControl automatically default to fixed sizes.

At runtime, my sizing code calculates a sizing factor based on the new width and height compared to the _defaultWidth and _defaultHeight elements.

+2


source


In a custom control, take advantage of the docking and binding of each control in the container. When the custom control is sized or sized, the content should automatically adjust. Then in code, all you have to do is set the size of the custom control.



+1


source







All Articles