问题
I have a user control that contains a collection of controls to be reused for presenting data on the UI. I've attempted implementing a "pop-out" option that will re-parent the control from another container on the form (a Panel, for example), create a new tab page, and then add the control to the tab page.
Unfortunately, when the control is added to the TabPage, its size appears to be locked to the way it was presented with the last parent.
I overrode the ParentChanged event to detect when the control was actually added to the TabPage. If I examine the size, attempt to set the size to the TabPage's ClientRectangle, and then re-examine the size - it does not change. Setting the Dock property does not alter this behavior (especially Fill).
protected override void OnParentChanged(EventArgs e)
{
if (this.Parent != null)
{
Size oldSize = this.Size;
this.Size = this.Parent.ClientRectangle.Size;
if (this.Size == oldSize)
{
// this is where we end up
throw new Exception("We didn't change size!");
}
}
}
回答1:
I suspect that if you have set the control to Dock then it probably will ignore attempts to change its size/position. Personally I'd turn off Dock/Anchor/AutoSize behaviour and just set the control's position and size manually. I've done this type of thing a lot and never had any problems, so I suspect you're just fighting an auto-layout option, and it's winning.
If you want Dock to do the work for you, you may need to kick the tab to initiate a recalculation of its layout? (there is a Control.LayoutEngine object that may be able to do this, but I'm just postulating a possible avenue of investigation here - I haven't tried it myself)
I hope that might give you some ideas, anyway...
回答2:
The control was first added to a container control. Diving into the bowels of the Container code, via Reflector, it was setting the min/max size values for my control that was being reparented. I had assumed, inaccurately, that the default min/max settings were left as the default from the designer. The container control unfortunately decided differently. Go, go, Reflector! This behavior was, of course, not documented.
Thank you all for your help.
来源:https://stackoverflow.com/questions/2419356/how-do-you-modify-a-control-that-has-been-re-parented-to-a-tabpage