C# – How to change the size of the child controls in a composite control in winforms

cnetwinforms

I basically created 2 child controls and I want to set their width to be equal to the width of the parent composite control. The problem is when I do this using the parent.Size property, it doesn't work. It only works once when you add the control.

Am I supposed to override an event not a property? I thought the property change would be signaled with a resize, right?

EDIT:

Here is the code, property doesn't work, but the OnResize event worked.

Q2: Shouldn't OnResize EventArgs e give me the new size?

public partial class CollapsableCtrl : UserControl
{
    public CollapsableCtrl ( )
    {
        this.ChildCtrl = new CustomCtrl ( );
        this.Size = new Size ( 181, 82 );
        this.Controls.Add ( this.ChildCtrl );
    }

    CustomCtrl ChildCtrl { get; set; }

    public new Size Size
    {
        get { return base.Size; }
        set
        {
            this.ChildCtrl.Size = value;
            Invalidate ( );
        }
    }

    protected override void OnResize ( EventArgs e )
    {
        base.OnResize ( e );
        this.ChildCtrl.Size = this.Size;
    }
}

Best Answer

Do you have properties like Dock or Anchor set for your child controls in a way that would prevent them from being resized to arbitrary dimensions? I do this all of the time and simply setting a child control's Size, Width, or Height property has always worked for me. If my guess is wrong, it would help us to see your code.

EDIT: After seeing your comment, I think that you should be using Dock and/or Anchor. This way, you can lay out the child controls first and then, when the parent is resized, the child controls will follow suit with no extra work on your end.