简体   繁体   English

Winform中停靠和锚定行为的组合

[英]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. 今天,我正在尝试使用c#将多个Windows控件顺序安装到面板上。 I would like them to dock to the top so that I can then use BringToFront() to stack them up. 我希望它们停靠在顶部,以便随后可以使用BringToFront()将它们堆叠起来。

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) 当前,停靠行为会强制将控件移至屏幕左侧(但是我需要调整大小并更改location属性)

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/ 编辑:这个标题很好地说明了我的问题: 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. 我只希望停靠的,堆叠的控件不绑定到面板的左边缘。

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. TableLayoutPanel可能在这里起作用,但我与一个简单的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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM