2012-05-15 27 views
12

Tengo un FlowLayout como sigue:Align controla a centrar en un FlowLayout

enter image description here

tengo que centrar todos los controles en el formulario (En otras palabras, digamos que el ancho de la forma es 200. btnOpt1 a btnOpt4 debe tener su Left a partir de 100 menos la mitad de la anchura de botón, no 0.)

+0

'FLowLayout' no está diseñado para eso. – SLaks

+0

@SLaks ¿me pueden recomendar una alternativa? – David

+0

intenta usar el panel – Likurg

Respuesta

22

Puede hacerlo de dos maneras pero con alguna limitación de cada una.

  1. Usando Anchor propiedad
  2. Usando el control de diseño con ayuda de Docking y Anchor propiedades.

Método 1: Ancla Propiedad

Controles están anclados de forma predeterminada a la parte superior izquierda de la forma que significa que cuando se cambia el tamaño de la forma, su distancia de la parte superior izquierda de la forma permanecerá constante. Si cambia el control de anclaje a la parte inferior izquierda, el control mantendrá la misma distancia desde la parte inferior y los lados izquierdos del formulario cuando se modifique el tamaño del formulario.

Al girar el anclaje en una dirección mantendrá el control centrado en en esa dirección al cambiar el tamaño.

Ejemplo:

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.Uso del control de diseño

  1. Agregue TableLayout Control, establezca su propiedad Dock en Rellenar.
  2. Añadir 1 fila con Tamaño Tipo Porcentaje del estilo 100%
  3. añadir 3 Columnas COLUMN1 (Tamaño Tipo - por ciento (100%)), la columna 2 (Tipo Tamaño - Absoluta (200 píxeles)), Columna3 (Tipo Tamaño - Porcentaje (100 %)).
  4. Ahora Añadir panel de control a la columna 2 y Set Es propiedad Dock para llenar
  5. añadir botones a este control y ajustar su tamaño como desee y puesto su propiedad Anchor AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top

Ejemplo - Designer.cs fragmento de código del formulario.

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; 

Esperanza esta ayuda ..

+0

Para mí fue suficiente con poner el AnchorStyle en 'None' (no es necesario configurarlo a la izquierda o cualquier otra cosa), me pregunto si me falta algo. – Antonio

+1

si está utilizando ese control en el panel de diseño de la tabla, entonces puede funcionar ... En el caso 2, puede funcionar correctamente si establece AnchorStype en 'None'. –

8

me gustaría ir con TableLayoutPanel lugar:

  • Ponga TableLayoutPanel en su forma
  • conjunto estilo muelle Fill al panel
  • dejar sólo una columna en el interior del panel
  • Crear fila para cada botón (y poner botones a celdas de la tabla)
  • Conjunto de tipo tamaño de fila Autosize
  • Conjunto de estilo muelle Fill a todos los botones, excepto el último uno
  • Conjunto de estilo muelle Top al último botón

BTW en su solución debe iterar sobre los controles de FlowLayoutPanel en lugar de controles de formulario. También considere restando margen horizontal y el relleno de ancho:

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

Pero yo le aconsejo que use TableLayoutPanel lugar.

+0

Gracias por su respuesta. +1 – David

0

O puede usar el diseño de cuadrícula en su lugar.

0

no soy buena en C#, pero también se puede añadir un panel en FlowLayoutPanel con el mismo ancho de FlowLayoutPanel. Luego puede agregar en el Panel creado en tiempo de ejecución el botón que desea y establecer el dock hacia la izquierda o hacia la derecha. Como desées. Déjame mostrarte un ejemplo en VB.NET y C# (convertidos en línea utilizados)

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#

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); 
[email protected](btn); 
2

He resuelto esto cambiando los valores de los márgenes . Sin embargo, estoy agregando mi contenido a un panel.

C#:

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

crear etiquetas de vacío con Name = lblEmpty y AutoSize = False. Pon este control primero en la lista de controles en FlowLayoutPanel1, luego agrega el código a continuación.

Ejemplo: Suponiendo tres etiquetas existentes en FlowLayoutPanel1, el resultado debería ser lblEmpty, LabelExisting1 y LabelExisting2, en ese orden.

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

Resolvé mi problema al crear este código.

en su caso con controles de botón, crear nuevas etiquetas con .Texto = "" (vacío) y poner a cada uno al comienzo de cada botón, etiquetas de nombres de la siguiente manera: lblEmpty1, lblEmpty2, lblEmpty3, lblEmpty4.

a continuación, añadir el siguiente código:

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 

Este botón central, el aumento de la anchura de la etiqueta vacía de acuerdo con la anchura de la FlowLayoutPanel1

Cuestiones relacionadas