tags:

views:

98

answers:

2

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

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

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

+1  A: 

In the user control, take advantage of the docking and anchoring properties of every control in the container. When the user control is sized or resized, the contents should adjust themselves automatically. Then in code, all you need to do is set the size of the user control.

Jon Seigel
Docking won't work for me, as I need to preserve the layout of the controls. Basically what I'm trying to accomplish is similar to the ComponentOne sizer. The code to do it isn't that difficult, I just a way to grab the original dimensions before resizing.
polara
Maybe I wasn't clear enough. You can use docking and/or anchoring. If you don't need to dock a child control, just use anchoring (Anchor property).
Jon Seigel
I tried setting the Anchor to [Top, Left, Bottom, Right] for all of the buttons on the UserControl. They resized but did not move and as a result ended up overlapping each other.
polara
Experiment with how the Anchor property works. It is rare to need to set it to enable anchoring on all four properties. For example, an OK button at the bottom-right of a resizable dialog would have Anchor set to [Bottom, Right] only.
Jon Seigel
+1  A: 

I ended up using my base control's dimensions as the fixed size for all inherited controls. This was fairly easy to do 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 BaseControl automatically default to its fixed dimensions.

At runtime, my resize code calculates a resize ratio based on the new Width and Height vs. the _defaultWidth and _defaultHeight members.

polara