如何使面板中的内容居中?

Sha*_*dow 3 c# alignment winforms

我有一个面板,我试图将控件居中。但显然,当面板停靠在控件边缘时,面板不喜欢填充。这是我的面板的当前代码:

buttonPanel = new Panel();
buttonPanel.Width = 300;
buttonPanel.Height = 50;
buttonPanel.Dock = DockStyle.Bottom;
buttonPanel.Padding = new Padding((this.ClientSize.Width - buttonPanel.Width) / 2, 0,
                                 (this.ClientSize.Width - buttonPanel.Width) / 2, 0);
buttonPanel.BackColor = Color.Transparent;
this.Controls.Add(buttonPanel);
Run Code Online (Sandbox Code Playgroud)

我在面板内放置了一个按钮。我对上述代码的期望是,该控件很好地放置在面板中心的 300 宽“矩形”的左侧。但按钮放置在最左侧,就好像忽略了填充:

在此输入图像描述

如何将一组按钮置于表单的中心?

Mah*_*nGM 5

设计时方法

在设计时,将按钮放入容器中并选择按钮。然后,使用布局工具栏中的水平居中垂直居中将按钮放在面板的中心。之后,转到按钮属性并从 Anchor 属性中删除每个锚点。

编码方式

Panel panel = new Panel();
panel.Size = new Size(300, 100);
panel.Dock = DockStyle.Bottom;

Button button = new Button();
button.Size = new Size(70, 25);
button.Location = new Point((panel.Width - button.Width) / 2, (panel.Height - button.Height) / 2);
button.Anchor = AnchorStyles.None;

panel.Controls.Add(button);
this.Controls.Add(panel);
Run Code Online (Sandbox Code Playgroud)