C# 将控件与 FlowLayout 中的中心对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10599961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:26:09  来源:igfitidea点击:

Align controls to center in a FlowLayout

c#.netwinforms

提问by David

I have a flowlayout as follows:

我有一个流程布局如下:

enter image description here

在此处输入图片说明

I need to center all the controls on the form (In other words, let's say the form's width is 200. btnOpt1 to btnOpt4 should have their Leftstarting at 100 minus half of the button width, not 0.)

我需要将窗体上的所有控件居中(换句话说,假设窗体的宽度为 200。btnOpt1 到 btnOpt4 的起始值应该是Left100 减去按钮宽度的一半,而不是 0。

采纳答案by Niranjan Singh

You can do it two ways but with some limitation of each one.

您可以通过两种方式进行操作,但每种方式都有一定的限制。

  1. Using Anchorproperty
  2. Using the layout control with help of Dockingand Anchorproperties.
  1. 使用Anchor财产
  2. DockingAnchor属性的帮助下使用布局控件。

Method 1: Anchor Property

方法一:锚点属性

Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.

Turning off the anchor in a direction will keep the control centred in that direction when resizing.

默认情况下,控件锚定在窗体的左上角,这意味着当窗体大小更改时,它们与窗体左上角的距离将保持不变。如果将控件锚点更改为左下角,则在调整窗体大小时,控件将与窗体底部和左侧保持相同的距离。

在调整大小时,关闭某个方向的锚点将使控件保持在该方向的中心。

Example :

例子 :

public TestForm12()
{
   InitializeComponent();

   Button btn = new Button();
   btn.Width = this.Width - 10;
   btn.Height = 20;
   btn.Left = (this.ClientSize.Width - btn.Width) / 2;
   btn.Top = (this.ClientSize.Height - btn.Height) / 2;
   btn.Text = "click me";
   this.Controls.Add(btn);
   btn.Anchor = AnchorStyles.None;               

}

2. Using the layout control

2.使用布局控件

  1. Add TableLayout Control, Set it's Dock property to Fill.
  2. Add 1 Row with Size Type style Percent 100%
  3. Add 3 Columns Column1(Size Type – Percent(100%)), Column2(Size Type – Absolute(200px)), Column3(Size Type – Percent(100%)).
  4. Now Add Panel Control to Column2 and Set it's Dock property to Fill
  5. Add Buttons to this control and set their Size as you want and Set Their Anchor Property to AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top
  1. 添加 TableLayout 控件,将其 Dock 属性设置为 Fill。
  2. 添加 1 行,大小类型样式百分比 100%
  3. 添加 3 列 Column1(Size Type – Percent(100%)), Column2(Size Type – Absolute(200px)), Column3(Size Type – Percent(100%))。
  4. 现在将 Panel Control 添加到 Column2 并将其 Dock 属性设置为 Fill
  5. 将按钮添加到此控件并根据需要设置它们的大小并将其锚属性设置为 AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top

Example - Designer.cs code snippet of the form.

示例 - 表单的 Designer.cs 代码片段。

private void InitializeComponent()
 {
     this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
     this.panel1 = new System.Windows.Forms.Panel();
     this.button1 = new System.Windows.Forms.Button();
     this.button2 = new System.Windows.Forms.Button();
     this.tableLayoutPanel1.SuspendLayout();
     this.panel1.SuspendLayout();
     this.SuspendLayout();
     // 
     // tableLayoutPanel1
     // 
     this.tableLayoutPanel1.ColumnCount = 3;
     this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
     this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 200F));
     this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
      this.tableLayoutPanel1.Controls.Add(this.panel1, 1, 0);
      this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
      this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
      this.tableLayoutPanel1.Name = "tableLayoutPanel1";
      this.tableLayoutPanel1.RowCount = 1;
      this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
      this.tableLayoutPanel1.Size = new System.Drawing.Size(284, 262);
      this.tableLayoutPanel1.TabIndex = 0;
      // 
      // panel1
      // 
      this.panel1.Controls.Add(this.button2);
      this.panel1.Controls.Add(this.button1);
      this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
      this.panel1.Location = new System.Drawing.Point(45, 3);
      this.panel1.Name = "panel1";
      this.panel1.Size = new System.Drawing.Size(194, 256);
      this.panel1.TabIndex = 0;
      // 
      // button1
      // 
      this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
    | System.Windows.Forms.AnchorStyles.Right)));
    this.button1.Location = new System.Drawing.Point(3, 9);
    this.button1.Name = "button1";
    this.button1.Size = new System.Drawing.Size(188, 23);
    this.button1.TabIndex = 0;
    this.button1.Text = "button1";
    this.button1.UseVisualStyleBackColor = true;
    // 
    // button2
    // 
    this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
    | System.Windows.Forms.AnchorStyles.Right)));
    this.button2.Location = new System.Drawing.Point(3, 38);
    this.button2.Name = "button2";
    this.button2.Size = new System.Drawing.Size(188, 23);
    this.button2.TabIndex = 0;
    this.button2.Text = "button1";
    this.button2.UseVisualStyleBackColor = true;
    // 
    // TestForm11
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(284, 262);
    this.Controls.Add(this.tableLayoutPanel1);
    this.Name = "TestForm11";
    this.Text = "TestForm11";
    this.tableLayoutPanel1.ResumeLayout(false);
    this.panel1.ResumeLayout(false);
    this.ResumeLayout(false);

}

 #endregion

private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button1;

Hope this help..

希望这有帮助..

回答by Sergey Berezovskiy

I'd go with TableLayoutPanelinstead:

我会用TableLayoutPanel代替:

  • Put TableLayoutPanel on your form
  • Set dock style Fillto panel
  • Leave only one column inside panel
  • Create row for every button (and put buttons to table cells)
  • Set row size type Autosize
  • Set dock style Fillto every button, except last one
  • Set dock style Topto last button
  • 将 TableLayoutPanel 放在您的表单上
  • 将停靠栏样式设置Fill为面板
  • 在面板内只留下一列
  • 为每个按钮创建行(并将按钮放在表格单元格中)
  • 设置行大小类型 Autosize
  • Fill为每个按钮设置停靠样式,最后一个除外
  • 将停靠样式设置Top为最后一个按钮

BTW in your solution you should iterate over flowLayoutPanel controls instead of form controls. Also consider subtracting horizontal margin and padding from width:

顺便说一句,在您的解决方案中,您应该迭代 flowLayoutPanel 控件而不是表单控件。还要考虑从宽度中减去水平边距和填充:

foreach (Control control in flowLayoutPanel.Controls)
{
    control.Size = new Size(flowLayoutPanel.Width - control.Margin.Horizontal,
                            control.Height); 
}

But I advise you to use TableLayoutPanel instead.

但我建议您改用 TableLayoutPanel。

回答by Nickon

Or you can use Grid layout instead.

或者您可以改用网格布局。

回答by Fábio Gaspar

I′m not good in C# but you can also add a panel in flowlayoutpanel with the same width of flowlayoutpanel. Then you can add in the Panel created in running time the button you want and set the dock to left or right. As you wish. Let me show a example in VB.net and C# (used online converts)

我不擅长 C# 但你也可以在 flowlayoutpanel 中添加一个与 flowlayoutpanel 宽度相同的面板。然后您可以在运行时创建的面板中添加您想要的按钮并将停靠栏设置为左侧或右侧。如你所愿。让我在 VB.net 和 C# 中展示一个示例(使用在线转换)

VB.net

VB.net

     Dim btn As New Button
            btn.Text = "Example"
            btn.Name = "Button"
            btn.Size = New Size(60,10)
            Dim panel As New Panel
            panel.Size = New Size(FlowLayoutPanel1.Width, 10) 'size of the flowlayoutpanel + height of button
            btn.Dock = DockStyle.Right
            FlowLayoutPanel1.Controls.Add(panel)
panel.controls.add(btn)

C#

C#

Button btn = new Button();
btn.Text = "Example";
btn.Name = "Button";
btn.Size = new Size(60, 10);
Panel panel = new Panel();
panel.Size = new Size(FlowLayoutPanel1.Width, 10);
//size of the flowlayoutpanel + height of button
btn.Dock = DockStyle.Right;
FlowLayoutPanel1.Controls.Add(panel);
panel.controls.@add(btn);

回答by Paulo de Barros

I solved this by changing the margin values. I am adding my content to a panel though.

我通过更改边距值解决了这个问题。不过,我正在将我的内容添加到面板中。

C#:

C#:

int horizontalMargin = (int)(0.5 * (this.containingPanelOrForm.Width - this.button.Width));
this.btnOptX.Margin = new Padding(horizontalMargin, 0, horizontalMargin, 0);

回答by Toto

Create empty Label with Name = lblEmpty and AutoSize = False. Put this control first in controls list in FlowLayoutPanel1, then add code below.

创建 Name = lblEmpty 和 AutoSize = False 的空标签。将此控件先放在 FlowLayoutPanel1 的控件列表中,然后在下面添加代码。

Example: Assuming three existing labels in FlowLayoutPanel1, the result should be lblEmpty, LabelExisting1, and LabelExisting2, in that order.

示例:假设 FlowLayoutPanel1 中存在三个标签,结果应该是 lblEmpty、LabelExisting1 和 LabelExisting2,按此顺序。

Dim MarginLabelEmpty As Integer = ((FlowLayoutPanel1.Width - (LabelExisting1.Width + LabelExisting2.Width)) / 2)
        lblEmpty.Width = MarginLabelEmpty

I solved my problem by creating this code.

我通过创建此代码解决了我的问题。

in your case with Button Controls, create 4new labels with .Text=""(empty) and put each one at the beginning of each button, naming labelsas follows: lblEmpty1, lblEmpty2, lblEmpty3, lblEmpty4.

在您使用按钮控件的情况下,创建4 个带有.Text=""( empty) 的新标签,并将每个标签放在每个按钮的开头,标签命名如下:lblEmpty1、lblEmpty2、lblEmpty3、lblEmpty4。

Then Add the following code:

然后添加以下代码:

Dim MarginLeftbtnOptAll As Integer = ((FlowLayoutPanel1.Width - btnOpt1.Width) / 2)
        lblEmpty1.AutoSize = False
        lblEmpty1.Width = MarginLeftbtnOptAll
        lblEmpty2.AutoSize = False
        lblEmpty2.Width = MarginLeftbtnOptAll
        lblEmpty3.AutoSize = False
        lblEmpty3.Width = MarginLeftbtnOptAll
        lblEmpty4.AutoSize = False
        lblEmpty4.Width = MarginLeftbtnOptAll

This center button, increasing the width of the empty label according to the width of the FlowLayoutPanel1

这个中心按钮,根据FlowLayoutPanel1的宽度增加空标签的宽度

回答by Ivan Ferrer Villa

Throwing the buttons directly to the form or a panel (not FlowLayoutPanel), and setting Anchor = Top(only Top) for all of them, they won't be centered but will always move proportional to the form's (or container's) sides when resizing.

将按钮直接扔到窗体或面板(不是 FlowLayoutPanel),并Anchor = Top为所有按钮设置(仅顶部),它们不会居中,但在调整大小时将始终与窗体(或容器)的边成比例移动。