使用面板和标签的用户控件水平动态添加

时间:2016-08-01 05:31:17

标签: c# winforms

我正在尝试使用Windows窗体PanelLabel的数量创建用户控件,并将一些文本水平地动态添加到Panel。我尝试使用下面的代码,Label被覆盖。

public partial class AllergyBar : Panel
{
    public AllergyBar()
        : base()
    {
        InitializeComponent();
    }

    int X = 0, Y=0;

    int height, width;
    public AllergyBar(List<String> lstAlerts)
        : base()
    {

        this.BackColor = System.Drawing.Color.WhiteSmoke;
        this.Name = "panel2";
        this.Size = new System.Drawing.Size(75, 23);
        this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
        foreach (string alert in lstAlerts)
        {
            Label AllergyLabel = new Label();
            AllergyLabel.Text = alert;
            width = AllergyLabel.Size.Width;
            Y = AllergyLabel.Location.Y;
            AllergyLabel.Location = new System.Drawing.Point(X+width, Y);
            AllergyLabel.Size = new System.Drawing.Size(75, 23);
            AllergyLabel.AutoSize = true;
            AllergyLabel.BorderStyle = BorderStyle.FixedSingle;
            AllergyLabel.Dock = DockStyle.Fill;
            this.Controls.Add(AllergyLabel);
        }       
        InitializeComponent();
    }
}

1 个答案:

答案 0 :(得分:0)

您必须在每个循环结束时更新X值:

if (context instanceof MyInterface) {
    ((MyInterface)context).requiredMethod()
}