1

我有一个Panel名为dockTop. 我添加了两个标签来表示Panel。我希望标签从左到右流动。这类似于人们对divcss 设置为的期望结果float: left......只是这是 winforms。

我有

   //I want DockStyle.Left, but that causes both controls to be of height, width = 0,0
   dockTop.Controls.Add(new Label() { Text = "one", Dock = DockStyle.Top });
   dockTop.Controls.Add(new Label() { Text = "two", Dock = DockStyle.Top }); 

Dock Top 工作正常,但这不是我想要的。如何在设置为 Dock Top 的面板中从左到右显示彼此相邻的标签?

4

3 回答 3

1

您必须通过设置位置自己放置它们。如果需要,适当地设置锚属性。或者,您可以使用 TableLayoutPanel 而不是 Panel

于 2013-01-04T23:06:37.623 回答
0

您必须设置DockDockStyle.TopDockStyle.Left

   dockTop.Controls.Add(new Label {Text = "one", Dock = DockStyle.Top | DockStyle.Left });
   dockTop.Controls.Add(new Label { Text = "two", Dock = DockStyle.Top | DockStyle.Left });

在此处输入图像描述

或者你可以AutoSize使用DockStyle.Left

   dockTop.Controls.Add(new Label {Text = "one", Dock = DockStyle.Left, AutoSize=true });
   dockTop.Controls.Add(new Label { Text = "two", Dock =  DockStyle.Left, AutoSize = true});

在此处输入图像描述

于 2013-01-04T22:28:31.310 回答
0

我使用Resize事件来完成这个任务。我希望它会帮助你。

static class Program
{
    static Label label1;
    static Label label2;
    static Form form1;
    static Rectangle rectForm;
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        form1 = new Form();
        rectForm = form1.ClientRectangle;
        Panel dockTopPanel = new Panel {Height = 100, Dock = DockStyle.Top, BackColor = Color.White };
        label1 = new Label { Text = "Label1", Dock = DockStyle.Left, BackColor = Color.Red, Width = rectForm.Width / 2 };
        label2 = new Label { Text = "Label2", Dock = DockStyle.Right, BackColor = Color.Blue, Width = rectForm.Width / 2 };
         label2.BringToFront();
        Control[] labels= {label1, label2};
        dockTopPanel.Controls.AddRange(labels);
        form1.Controls.Add(dockTopPanel);
        form1.Resize += new EventHandler(form1_Resize);
        Application.Run(form1);
    }

    static void form1_Resize(object sender, EventArgs e)
    {
        rectForm = form1.ClientRectangle;
        label1.Width = (rectForm.Width / 2) + 1;
        label2.Width = (rectForm.Width / 2) + 1;
    }
}
于 2013-01-04T23:50:20.250 回答