简体   繁体   English

Windows窗体中的布局困难

[英]Difficulty with Layouts in Windows Forms

I'm programming an application in C# with Windows Forms. 我正在使用Windows窗体的C#编写应用程序。 It is a form with a menu, a tabbed pane, a grid and a status bar. 它是带有菜单,选项卡式窗格,网格和状态栏的表单。 I'd like the controls to show up correctly even when resizing the window. 我希望控件即使在调整窗口大小时也能正确显示。 If I add the controls to the form without using any layout panel, the menu bar shows up on top of the tabs (see Figure 1). 如果我在不使用任何布局面板的情况下将控件添加到窗体,则菜单栏将显示在选项卡的顶部(请参见图1)。 On the other hand, if I use a FlowLayoutPanel in order to add the components from top to bottom, the controls don't fill the available space (see Figure 2). 另一方面,如果我使用FlowLayoutPanel为了从上到下添加组件,则控件不会填充可用空间(请参见图2)。

EDIT: I couldn't solve it using a TableLayoutPanel. 编辑:我无法使用TableLayoutPanel解决它。 The vertical space isn't filled either. 垂直空间也未填充。 See Figure 3. 参见图3。

What may be the problem? 可能是什么问题? What is the usual way to work with Layouts in Windows Forms? 在Windows窗体中使用布局的通常方法是什么? Thank you in advance. 先感谢您。

没有布局面板的屏幕截图

使用FlowLayoutPanel截屏

使用TableLayoutPanel截屏

The code is the following: 代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AGAPconsole;

namespace AGAP
{
public partial class MainForm : Form
{

    private String user;
    private ClassDatabase db;

    private TableLayoutPanel mainPanel;
    private TabControl mainTabControl;
    private TabPage mainTabPage;

    // Grid de actuaciones
    private DataGridView actuacionesGrid;
    private ContextMenuStrip actuacionesContextMenuStrip;
    private ToolStripMenuItem verTramitesMenuItem;
    private ToolStripMenuItem verEncargosMenuItem;
    private ToolStripMenuItem verTrabajosMenuItem;
    private ToolStripMenuItem verDatosObraMenuItem;

    // Barra de estado
    private StatusStrip mainStatusStrip;
    private ToolStripStatusLabel mainStatusLabel;

    // Menu
    private MenuStrip mainMenuStrip;
    private ToolStripMenuItem archivoMenuItem;
    private ToolStripMenuItem salirMenuItem;
    private ToolStripMenuItem abrirMenuItem;

    // Importacion
    private OpenFileDialog openFileDialog;

    // Users
    public static String USER_CONSULTA_CORUNA = "Delegación C (R)";
    public static String USER_EDICION_CORUNA = "Delegación C (RW)";
    public static String USER_CONSULTA_OURENSE = "Delegación OU-LU (R)";
    public static String USER_EDICION_OURENSE = "Delegación OU-LU (RW)";
    public static String USER_CONSULTA_PONTEVEDRA = "Delegación PO (R)";
    public static String USER_EDICION_PONTEVEDRA = "Delegación PO (RW)";
    public static String USER_IMPORTACION = "Importación";
    public static String USER_ZONA = "Zona";

    public static String[] USERS = { USER_ZONA, USER_CONSULTA_CORUNA, 
                                       USER_EDICION_CORUNA, USER_CONSULTA_OURENSE, 
                                       USER_EDICION_OURENSE, USER_CONSULTA_PONTEVEDRA, 
                                       USER_EDICION_PONTEVEDRA, USER_IMPORTACION };

    public MainForm(String user)
    {
        this.user = user;
        db = new ClassDatabase();
        //InitializeComponent();
        //this.AutoScaleDimensions = new SizeF(6F, 13F);
        this.AutoScaleMode = AutoScaleMode.Font;
        this.ClientSize = new Size(984, 762);
        this.Name = "MainForm";
        //this.StartPosition = FormStartPosition.CenterScreen;
        this.Text = "AGAP";
        this.WindowState = FormWindowState.Maximized;
        this.BackColor = SystemColors.Window;

        this.Controls.Add(CreateMainPanel());

        // Menu
        mainPanel.Controls.Add(CreateMainMenuStrip());

        // Contenido dependiendo del usuario

        // El menu tendra Archivo -> Salir a no ser que sea el usuario de importacion,
        // que tendra mas cosas.
        if (!user.Equals(USER_IMPORTACION))
        {
            //CreateArchivoSalir();
            CreateSalir();
        }

        if (user.Equals(USER_ZONA))
        {
            this.Text = "AGAP Visualización de datos";
            InitVisualizacion();
        }

        if (user.Equals(USER_IMPORTACION))
        {
            this.Text = "AGAP Importación de datos";
            InitImportacion();
        }

        // Barra de estado
        mainPanel.Controls.Add(CreateMainStatusStrip());
        this.mainStatusLabel.Text = "Autenticado como " + user;
    }

    private void InitImportacion()
    {
        CreateOpenFileDialog();
        // this.Controls.Add(CreateMainPanel());
        // mainPanel.Controls.Add(CreateMainMenuStrip());
        mainMenuStrip.Items.Add(CreateArchivoMenuItem());
        archivoMenuItem.DropDownItems.Add(CreateAbrirMenuItem());
        archivoMenuItem.DropDownItems.Add("-");
        archivoMenuItem.DropDownItems.Add(CreateSalirMenuItem());
    }

    private void InitVisualizacion()
    {
        // this.Controls.Add(CreateMainPanel());
        mainPanel.Controls.Add(CreateMainTabControl());
        mainTabPage.Controls.Add(CreateActuacionesGrid());
        mainTabPage.Text = "Actuaciones";
        actuacionesGrid.Name = "actuacionesGrid";
    }

    private OpenFileDialog CreateOpenFileDialog()
    {
        if (openFileDialog == null)
        {
            openFileDialog = new OpenFileDialog();
            openFileDialog.AutoUpgradeEnabled = true;
            openFileDialog.Filter = "Archivos CSV, Excel (*.csv, *.xls, *.xlsx)|*.csv;*.xls;*.xlsx|Todos los archivos (*.*)|*.*";
            openFileDialog.ValidateNames = true;
        }
        return openFileDialog;
    }

    private ToolStripMenuItem CreateAbrirMenuItem()
    {
        if (abrirMenuItem == null)
        {
            abrirMenuItem = new ToolStripMenuItem();
            abrirMenuItem.Name = "abrirMenuItem";
            abrirMenuItem.Text = "&Abrir...";
            abrirMenuItem.Click += new EventHandler(abrirMenuItem_Click);
            abrirMenuItem.ShortcutKeys = ((Keys)((Keys.Control | Keys.O)));
        }
        return abrirMenuItem;
    }

    private void abrirMenuItem_Click(object sender, EventArgs e)
    {
        DialogResult result = openFileDialog.ShowDialog();
        if (result == DialogResult.OK)
        {
            bool ret = false;
            string file = openFileDialog.FileName;
            if (file.EndsWith(".csv"))
            {
                ret = CSVparser.parseCSV(file);
            }
            else
            {
                // Parse Excel file
            }
            string messageBoxText;
            MessageBoxIcon icon;
            if (ret)
            {
                messageBoxText = "Importación finalizada";
                icon = MessageBoxIcon.Information;
            }
            else
            {
                messageBoxText = "La importación ha fracasado. Se ha producido un error.";
                icon = MessageBoxIcon.Warning;
            }
            string caption = "AGAP Importación de datos";
            MessageBoxButtons buttons = MessageBoxButtons.OK;
            MessageBox.Show(messageBoxText, caption, buttons, icon);
        }
    }

    private void CreateSalir()
    {
        mainMenuStrip.Items.Add(CreateSalirMenuItem());
    }

    private void CreateArchivoSalir()
    {
        mainMenuStrip.Items.Add(CreateArchivoMenuItem());
        archivoMenuItem.DropDownItems.Add(CreateSalirMenuItem());
    }

    #region Creacion de controles
    private MenuStrip CreateMainMenuStrip()
    {
        if (mainMenuStrip == null)
        {
            mainMenuStrip = new MenuStrip();
            mainMenuStrip.Name = "mainMenuStrip";
            mainMenuStrip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
        }
        return mainMenuStrip;
    }

    private ToolStripMenuItem CreateArchivoMenuItem()
    {
        if (archivoMenuItem == null)
        {
            archivoMenuItem = new ToolStripMenuItem();
            archivoMenuItem.Name = "archivoToolStripMenuItem";
            archivoMenuItem.Text = "&Archivo";

        }
        return archivoMenuItem;
    }

    private ToolStripMenuItem CreateSalirMenuItem()
    {
        if (salirMenuItem == null)
        {
            salirMenuItem = new ToolStripMenuItem();
            salirMenuItem.Name = "salirToolStripMenuItem";
            salirMenuItem.Text = "&Salir...";
            salirMenuItem.Click += new EventHandler(salirMenuItem_Click);
            salirMenuItem.ShortcutKeys = ((Keys)((Keys.Control | Keys.Q)));
        }
        return salirMenuItem;
    }

    private StatusStrip CreateMainStatusStrip()
    {
        if (mainStatusStrip == null)
        {
            mainStatusStrip = new StatusStrip();
            mainStatusStrip.Name = "mainStatusStrip";
            mainStatusStrip.BackColor = SystemColors.Window;
            mainStatusStrip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
            mainStatusStrip.Items.Add(CreateMainStatusLabel());
        }
        return mainStatusStrip;
    }

    private ToolStripStatusLabel CreateMainStatusLabel()
    {
        if (mainStatusLabel == null)
        {
            mainStatusLabel = new ToolStripStatusLabel();
            mainStatusLabel.Name = "mainStatusLabel";
            mainStatusLabel.BackColor = SystemColors.Window;
        }
        return mainStatusLabel;
    }
    private TableLayoutPanel CreateMainPanel()
    {
        if (mainPanel == null)
        {
            mainPanel = new TableLayoutPanel();
            mainPanel.Name = "mainPanel";
            mainPanel.Dock = DockStyle.Fill;
            //mainPanel.FlowDirection = FlowDirection.TopDown;
            mainPanel.Size = new Size(1280, 1024);
            mainPanel.ColumnCount = 1;
            mainPanel.RowCount = 3;
        }
        return mainPanel;
    }

    private TabControl CreateMainTabControl()
    {
        if (mainTabControl == null)
        {
            mainTabControl = new TabControl();
            mainTabControl.Controls.Add(CreateMainTabPage());
            //mainTabControl.Location = new Point(0, 0);
            mainTabControl.Name = "mainTabControl";
            mainTabControl.SelectedIndex = 0;
            //this.mainTabControl.Size = new System.Drawing.Size(745, 559);
            //mainTabControl.TabIndex = 0;
            //mainTabControl.Size = new Size(1280, 1024);
            mainTabControl.Dock = DockStyle.Fill;
            //mainTabControl.Dock = DockStyle.Bottom | DockStyle.Top | DockStyle.Left;
            //mainTabControl.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right ;
            mainTabControl.MouseClick += new MouseEventHandler(mainTabControl_MouseClick);
        }
        return mainTabControl;
    }

    private void mainTabControl_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            ContextMenuStrip cms = CreateMainTabControlContextMenuStrip();
            cms.Show(mainTabControl, e.Location);
        }
        if (e.Button == MouseButtons.Middle)
        {
            if (mainTabControl.SelectedIndex != 0)
            {
                mainTabControl.TabPages.Remove(mainTabControl.SelectedTab);
            }
        }
    }

    private ContextMenuStrip CreateMainTabControlContextMenuStrip()
    {
        ContextMenuStrip cms = new ContextMenuStrip();
        cms.Items.AddRange(new ToolStripMenuItem[] { CreateCloseTabMenuItem() });
        return cms;
    }

    private ToolStripMenuItem CreateCloseTabMenuItem()
    {
        var closeTabMenuItem = new ToolStripMenuItem();
        closeTabMenuItem.Text = "&Cerrar pestaña";
        closeTabMenuItem.Click += new EventHandler(closeTabMenuItem_Click);
        //closeTabMenuItem.ShortcutKeys = ((Keys)((Keys.Control | Keys.F4)));
        return closeTabMenuItem;
    }

    private void closeTabMenuItem_Click(object sender, EventArgs e)
    {
        if (mainTabControl.SelectedIndex != 0)
        {
            mainTabControl.TabPages.Remove(mainTabControl.SelectedTab);
        }
    }

    private TabPage CreateTabPage()
    {
        var tabPage = new TabPage();
        //tabPage.Location = new Point(4, 22);
        //tabPage.Padding = new Padding(3);
        //tabPage.UseVisualStyleBackColor = true;
        return tabPage;
    }

    private TabPage CreateMainTabPage()
    {
        if (mainTabPage == null)
        {
            mainTabPage = CreateTabPage();
            mainTabPage.Name = "mainTabPage";
            mainTabPage.Text = "Actuaciones";
            //mainTabPage.TabIndex = 0;
        }
        return mainTabPage;
    }

    private DataGridView CreateGrid()
    {
        DataGridView grid = new DataGridView();
        // Propiedades fijas
        grid.AllowUserToOrderColumns = true;
        grid.RowHeadersVisible = false;
        grid.StandardTab = false;
        grid.ReadOnly = true;
        grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        grid.MultiSelect = false;
        grid.ScrollBars = ScrollBars.Both;
        grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
        grid.BackgroundColor = SystemColors.Window;

        // Propiedades dudosas
        //grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        grid.Dock = DockStyle.Fill;
        //grid.Location = new Point(0, 0);
        //grid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
        grid.TabIndex = 0;
        //grid.Size = new Size(1280, 1024);
        //grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        //grid.AutoSize = true;

        //grid.PerformLayout();

        return grid;
    }

    private DataGridView CreateActuacionesGrid()
    {
        if (actuacionesGrid == null)
        {
            actuacionesGrid = CreateGrid();
            actuacionesGrid.MouseDown += new MouseEventHandler(actuacionesGrid_MouseDown);
            actuacionesGrid.DataSource = ComunicacionBD.SelectActuaciones(db).Tables[0].DefaultView;
            actuacionesGrid.ContextMenuStrip = CreateActuacionesContextMenuStrip();
        }
        return actuacionesGrid;
    }

    private ContextMenuStrip CreateActuacionesContextMenuStrip()
    {
        if (actuacionesContextMenuStrip == null)
        {
            actuacionesContextMenuStrip = new ContextMenuStrip();
            actuacionesContextMenuStrip.Name = "actuacionesContextMenuStrip";
            actuacionesContextMenuStrip.Items.AddRange(new ToolStripMenuItem[] { CreateVerTramitesMenuItem(),
                CreateVerEncargosMenuItem(), CreateVerTrabajosMenuItem(), CreateVerDatosObraMenuItem()});
        }
        return actuacionesContextMenuStrip;
    }

    private ToolStripMenuItem CreateVerDatosObraMenuItem()
    {
        if (verDatosObraMenuItem == null)
        {
            verDatosObraMenuItem = new ToolStripMenuItem();
            verDatosObraMenuItem.Name = "verDatosObraMenuItem";
            verDatosObraMenuItem.Text = "Ver &datos de obra";
            verDatosObraMenuItem.Click += new EventHandler(verDatosObraMenuItem_Click);
            verDatosObraMenuItem.ShortcutKeys = ((Keys)((Keys.Control | Keys.D)));
        }
        return verDatosObraMenuItem;
    }

    private ToolStripMenuItem CreateVerTramitesMenuItem()
    {
        if (verTramitesMenuItem == null)
        {
            verTramitesMenuItem = new ToolStripMenuItem();
            verTramitesMenuItem.Name = "verTramitesMenuItem";
            verTramitesMenuItem.Text = "Ver &trámites";
            verTramitesMenuItem.Click += new EventHandler(verTramitesMenuItem_Click);
            verTramitesMenuItem.ShortcutKeys = ((Keys)((Keys.Control | Keys.T)));
        }
        return verTramitesMenuItem;
    }

    private ToolStripMenuItem CreateVerEncargosMenuItem()
    {
        if (verEncargosMenuItem == null)
        {
            verEncargosMenuItem = new ToolStripMenuItem();
            verEncargosMenuItem.Name = "verEncargosMenuItem";
            verEncargosMenuItem.Text = "Ver &encargos";
            verEncargosMenuItem.Click += new EventHandler(verEncargosMenuItem_Click);
            verEncargosMenuItem.ShortcutKeys = ((Keys)((Keys.Control | Keys.E)));
        }
        return verEncargosMenuItem;
    }

    private ToolStripMenuItem CreateVerTrabajosMenuItem()
    {
        if (verTrabajosMenuItem == null)
        {
            verTrabajosMenuItem = new ToolStripMenuItem();
            verTrabajosMenuItem.Name = "verTrabajosMenuItem";
            verTrabajosMenuItem.Text = "Ver t&rabajos";
            verTrabajosMenuItem.Click += new EventHandler(verTrabajosMenuItem_Click);
            verTrabajosMenuItem.ShortcutKeys = ((Keys)((Keys.Control | Keys.W)));
        }
        return verTrabajosMenuItem;
    }

    #endregion

    #region Event Handlers
    private void actuacionesGrid_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            var hti = actuacionesGrid.HitTest(e.X, e.Y);
            actuacionesGrid.ClearSelection();
            actuacionesGrid.Rows[hti.RowIndex].Selected = true;
        }
    }

    private void verTramitesMenuItem_Click(object sender, EventArgs e)
    {
        // Coger la actuacion seleccionada.
        //Actuacion act = (Actuacion) actuacionesGrid.CurrentRow.DataBoundItem;
        string obraid = actuacionesGrid.CurrentRow.Cells["ObraId"].Value.ToString();

        // Crear la pestaña.
        var tabPage = CreateTabPage();
        tabPage.Name = "tramitesTabPage" + obraid;
        tabPage.Text = "Trámites actuación " + obraid;
        mainTabControl.TabPages.Add(tabPage);
        mainTabControl.SelectedTab = tabPage;

        // Crear el FlowLayoutPanel
        //var panel = new FlowLayoutPanel();
        //tabPage.Controls.Add(panel);

        // Crear el panel con las labels de la actuacion
        //panel.Controls.Add(CreateActuacionPanel(act));

        // Crear la tabla
        var grid = CreateTramitesGrid();
        grid.DataSource = ComunicacionBD.SelectTramites(db, obraid).Tables[0].DefaultView;
        tabPage.Controls.Add(grid);
    }

    private void verDatosObraMenuItem_Click(object sender, EventArgs e)
    {
        // Coger la actuacion seleccionada.
        //Actuacion act = (Actuacion) actuacionesGrid.CurrentRow.DataBoundItem;
        string obraid = actuacionesGrid.CurrentRow.Cells["ObraId"].Value.ToString();

        // Crear la pestaña.
        var tabPage = CreateTabPage();
        tabPage.Name = "datosObraTabPage" + obraid;
        tabPage.Text = "Datos de obra " + obraid;
        mainTabControl.TabPages.Add(tabPage);
        mainTabControl.SelectedTab = tabPage;

        // Crear el FlowLayoutPanel
        //var panel = new FlowLayoutPanel();
        //tabPage.Controls.Add(panel);

        // Crear el panel con las labels de la actuacion
        //panel.Controls.Add(CreateActuacionPanel(act));

        // Crear la tabla
        var grid = CreateTramitesGrid();
        grid.DataSource = ComunicacionBD.SelectDatosObra(db, obraid).Tables[0].DefaultView;
        tabPage.Controls.Add(grid);
    }


    private Panel CreateActuacionPanel(Actuacion act)
    {
        var actuacionPanel = new FlowLayoutPanel();
        actuacionPanel.FlowDirection = FlowDirection.LeftToRight;

        var actuacionLabel = new Label();
        actuacionLabel.Text = "Actuación: " + act.ActuacionId;

        var descLabel = new Label();
        descLabel.Text = "Descripción: " + act.Descripcion;

        actuacionPanel.Controls.Add(actuacionLabel);
        actuacionPanel.Controls.Add(descLabel);
        return actuacionPanel;
    }

    private DataGridView CreateTramitesGrid()
    {
        var grid = CreateGrid();
        return grid;
    }

    private DataGridView CreateTrabajosGrid()
    {
        var grid = CreateGrid();
        return grid;
    }

    private void verEncargosMenuItem_Click(object sender, EventArgs e)
    {
        // Coger la actuacion seleccionada.
        //Actuacion act = (Actuacion) actuacionesGrid.CurrentRow.DataBoundItem;
        string obraid = actuacionesGrid.CurrentRow.Cells["ObraId"].Value.ToString();

        // Crear la pestaña.
        var tabPage = CreateTabPage();
        tabPage.Name = "encargosTabPage" + obraid;
        tabPage.Text = "Encargos actuación " + obraid;
        mainTabControl.TabPages.Add(tabPage);
        mainTabControl.SelectedTab = tabPage;

        // Crear el FlowLayoutPanel
        //var panel = new FlowLayoutPanel();
        //tabPage.Controls.Add(panel);

        // Crear el panel con las labels de la actuacion
        //panel.Controls.Add(CreateActuacionPanel(act));

        // Crear la tabla
        var grid = CreateTrabajosGrid();
        grid.DataSource = ComunicacionBD.SelectEncargos(db, obraid).Tables[0].DefaultView;
        tabPage.Controls.Add(grid);
    }

    private void verTrabajosMenuItem_Click(object sender, EventArgs e)
    {
        // Coger la actuacion seleccionada.
        //Actuacion act = (Actuacion) actuacionesGrid.CurrentRow.DataBoundItem;
        string obraid = actuacionesGrid.CurrentRow.Cells["ObraId"].Value.ToString();

        // Crear la pestaña.
        var tabPage = CreateTabPage();
        tabPage.Name = "trabajosTabPage" + obraid;
        tabPage.Text = "Trabajos actuación " + obraid;
        mainTabControl.TabPages.Add(tabPage);
        mainTabControl.SelectedTab = tabPage;

        // Crear el FlowLayoutPanel
        //var panel = new FlowLayoutPanel();
        //tabPage.Controls.Add(panel);

        // Crear el panel con las labels de la actuacion
        //panel.Controls.Add(CreateActuacionPanel(act));

        // Crear la tabla
        var grid = CreateTrabajosGrid();
        grid.DataSource = ComunicacionBD.SelectTrabajos(db, obraid).Tables[0].DefaultView;
        tabPage.Controls.Add(grid);
    }

    private void salirMenuItem_Click(object sender, EventArgs e)
    {
        Close();
    }
    #endregion

    // Por culpa de tener un Form de Login antes, hay que hacer este metodo asi.
    // Seguramente hay formas mejores de hacerlo, pero esto funciona.
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);

        if (e.CloseReason == CloseReason.WindowsShutDown)
        {
            return;
        }

        switch (MessageBox.Show(this, "¿Salir ahora?", "Salir", MessageBoxButtons.YesNo))
        {
            case DialogResult.Yes:
                break;
            default:
                e.Cancel = true;
                break;
        }
        if (!e.Cancel)
        {
            Environment.Exit(0);
        }
    }
}

} }

You have to use TableLayoutPanel instead of FlowLayoutPanel . 您必须使用TableLayoutPanel而不是FlowLayoutPanel

FlowLayoutPanel is used to form a stack of controls, one after another and solving wrapping. FlowLayoutPanel用于形成一堆控件,一个接一个,另一个用于包装。 TableLayoutPanel is a table with all sort of cell manipulations: extending to more cells vertically/horizontally, sizing, proportioning, etc. TableLayoutPanel是具有各种单元格操作的表格:垂直/水平扩展到更多单元格,调整大小,比例等。

For your task you will need TableLayoutPanel : 对于您的任务,您将需要TableLayoutPanel

  • Only one column; 只有一列;
  • 3 rows: for menu (autosize), for DataGridView (inside tabbed pane I guess?) (100%) and for status bar (autosize). 3行:用于菜单(自动调整大小),用于DataGridView (我猜在选项卡式窗格内)(100%)和用于状态栏(自动调整大小)。

在此处输入图片说明

Then set TableLayoutPanel docking to Fill and it should be pretty much about it. 然后将TableLayoutPanel停靠设置为Fill ,应该差不多了。

A tip: make sure you put controls inside cells before setting row to AutoSize . 提示:在将row设置为AutoSize之前,请确保将控件放在单元格中。

Point here is what TableLayoutPanel can assign specified percentage (in our case 100% or any other value will do, as there is only 1 row requesting percentage of size) and will increase/decrease cell size if size of panel is changed. 这里要指出的是TableLayoutPanel可以分配指定的百分比(在我们的示例中为100%或任何其他值,因为只有1行要求显示尺寸百分比),并且如果更改面板的尺寸,则将增加/减小单元格的尺寸。 Then you can use cell to dock/anchor control inside the cell in a way you like. 然后,您可以使用单元以自己喜欢的方式在单元内部停靠/锚定控制。 For this see @Hassan Nisar answer, it will not solve your issue though in its current form, despite it was already upvoted, perhaps as being useful ;-). 为此,请参阅@Hassan Nisar的答案,尽管它已经被投票通过,但仍不能解决您的问题,尽管它已经被支持,也许有用;-)。

You have to set Anchor property of FlowLayoutPanel. 您必须设置FlowLayoutPanel的Anchor属性。

By using this property you can set the edges of the container to which a control is bound and determines how a control is resized with its parent. 通过使用此属性,可以设置控件绑定到的容器的边缘,并确定如何使用其父控件调整控件的大小。

For Anchoring and Docking child controls : 对于锚定和停靠子控件

Here is MSDN example on How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control . 这是有关如何:FlowLayoutPanel控件中的锚定和停靠子控件的 MSDN示例。

UPDATE : 更新

This is important note on MSDN regarding FlowLayoutPanel : 这是MSDN上有关FlowLayoutPanel重要说明:

General rule for anchoring and docking in the FlowLayoutPanel control: for vertical flow directions, the FlowLayoutPanel control calculates the width of an implied column from the widest child control in the column. FlowLayoutPanel控件中锚固和停靠的一般规则:对于垂直流向,FlowLayoutPanel控件根据列中最宽的子控件计算隐含列的宽度。 All other controls in this column with Anchor or Dock properties are aligned or stretched to fit this implied column. 该列中具有Anchor或Dock属性的所有其他控件均已对齐或拉伸以适合此隐含列。 The behavior works in a similar way for horizontal flow directions. 对于水平流向,此行为以类似的方式起作用。 The FlowLayoutPanel control calculates the height of an implied row from the tallest child control in the row, and all docked or anchored child controls in this row are aligned or sized to fit the implied row. FlowLayoutPanel控件根据该行中最高的子控件计算隐含行的高度,并且该行中所有停靠或锚定的子控件的对齐或大小均适合隐含行。

For vertical flow direction : 对于垂直流向
Supply Size of widest child control. 最广泛的子控件的供应大小。 (For example control can be datagridview1 in your case. (例如,根据您的情况,控件可以是datagridview1

For horizontal flow direction : 对于水平流向
Supply Size of tallest child control. 最高子控件的供应大小。

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

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