Search code examples
c#winformsdocking

Combination of docking and anchoring behaviours in winforms


Today I'm trying to use c# to fit a number of windows controls onto a panel sequentially. I would like them to dock to the top so that I can then use BringToFront() to stack them up.

HOWEVER I would also like them to be centred. Currently, docking behaviour forces the controls to the left of the screen (however much I resize and change the location property)

I then tried to anchor my controls to the top of the panel instead. This enabled the controls to be centred and also let me resize them but anchoring has no stacking behaviour and each control overwrites the previous one.

I have researched this extensively for hours and have found no answers to this question. Is it possible to use either or both of these properties to stack my controls in the centre of the panel?

My code currently stands as so:

//Docking 
userControl.Dock = DockStyle.Top;
userControl.Width = 633;
userControl.Left = (pnlRules.Width - userControl.Width) / 2; //doesn't work
Point location = new Point(((pnlRules.Width - userControl.Width) / 2), 0);
userControl.Location = location; //doesn't work
userControl.BringToFront();

OR

//Anchoring
userControl.Anchor = AnchorStyles.Top;
Point location = new Point(((pnlRules.Width - userControl.Width) / 2), 0);
userControl.Location = location;
userControl.BringToFront(); //doesn't work

My outputs are either stacked controls bound to the left panel edge (docking) or overlapping controls beautifully resized and centred (anchoring)

Thanks :) Anya

Edit: This captions my problem quite nicely: http://www.techrepublic.com/article/manage-winform-controls-using-the-anchor-and-dock-properties/

This explains that using docking, the controls can be stacked next to each other. I would just like the docked, stacked controls to not be bound to the left edge of the panel.


Solution

  • There is no way to use a combination of docking and anchoring. A TableLayoutPanel may have worked here but I was tied to a simple Panel.

    The fix was to use padding to force the control to centre:

    userControl.Dock = DockStyle.Top;
    pnlParent.Padding = new Padding((pnlParent.Width - userControl.Width) / 2, 0, 0, 0);
    userControl.BringToFront();