Reputation: 575
I want to make some controls (specifically: Button, Label and Panel) to become dependent on the size of their parent. So a button might be 0.1 times the width of the parent, 0.05 the height, and be positioned in 0.3 times the width and 0.2 times the height. Now I have 2 problems:
First I want to change the behaviour of the Control class into a sort of 'relative size and relative position'-Control. This would be very easy if the Control class had an 'onParentResized' method I could override, but it hasn't. So now my solution is this
class RelativeControl : Control
{
Control previousParent;
double relativeWidth, relativeHeight, relativeX, relativeY;
public RelativeControl(double RelativeWidth, double RelativeHeight, double RelativeX, double RelativeY)
{
// the arguments need to be between 0 and 1 normally, or the control is
// garanteed to be partially offscreen
this.relativeWidth = RelativeWidth;
this.relativeHeight = RelativeHeight;
this.relativeX = RelativeX;
this.relativeY = RelativeY;
}
protected override void OnParentChanged(EventArgs e)
{
if(previousParent != null)
{
previousParent.Resize -= new EventHandler(parentResized);
}
if(this.Parent != null)
{
this.Parent.Resize += parentResized;
}
this.previousParent = this.Parent;
}
private void parentResized(Object o, EventArgs e)
{
this.Width = (int)(this.Parent.Width * this.relativeWidth);
this.Height = (int)(this.Parent.Width * this.relativeHeight);
this.Location = new Point((int)(this.Parent.Width * this.relativeX), (int)(this.Parent.Height * this.relativeY));
}
}
Is this a good solution?
Second problem: I want to make the Button-class (as well as the Panel and Label class) to extend this new version of control. However this isn't possible as far as I know. My only option seems to be to make 3 classes and literally find-and-replace 'Control' by "Label", "Button" and "Panel" to get the result I want.
What should I be doing here?
Upvotes: 1
Views: 5396
Reputation: 4892
I think you are after TableLayoutPanel control. Happily on .NET platform do not have to worry anymore about child controls resizing or repositioning to the parent. You have to make extensive use of the Dock and Anchor properties of the child controls. You can start with the links but there are many tutorials about them on the web.
Anchor and Dock Child Controls
Create a Resizable Windows Form
Upvotes: 2