如何在停靠在顶部的面板中并排显示两个Label控件?

时间:2013-01-04 22:20:32

标签: c# winforms

我有一个名为Panel的{​​{1}}对象。我向dockTop添加了两个标签。我希望标签从左向右流动。这类似于人们期望Panel的css设置为div ...只有这是winforms。

我有

float: left

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您必须将Dock设置为DockStyle.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 });

enter image description here

或者您可以将AutoSizeDockStyle.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});

enter image description here

答案 2 :(得分: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;
    }
}