向右移动标签以避免重叠

时间:2013-08-28 22:52:59

标签: c# winforms label overlapping

我有两个标签彼此相邻。这些标签的值在运行时更改。 现在,如果第一个标签的文本很长,那么它会与第二个标签重叠。

我想要的是向右移动以避免重叠的第二个标签。

这可能吗?

这是我的代码:

 // 
        // labelName
        // 
        this.labelName.AutoSize = true;
        this.labelName.BackColor = System.Drawing.Color.Transparent;
        this.labelName.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.labelName.ForeColor = System.Drawing.Color.White;
        this.labelName.Location = new System.Drawing.Point(6, 1);
        this.labelName.Name = "labelName";
        this.labelName.Size = new System.Drawing.Size(93, 16);
        this.labelName.TabIndex = 55;
        this.labelName.Tag = "useHeaderImage Core";
        this.labelName.Text = "Name";
        // 
        // labelShareSize
        // 
        this.labelShareSize.AutoSize = true;
        this.labelShareSize.BackColor = System.Drawing.Color.Transparent;
        this.labelShareSize.Font = new System.Drawing.Font("Tahoma", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
        this.labelShareSize.ForeColor = System.Drawing.Color.White;
        this.labelShareSize.Location = new System.Drawing.Point(206, 3);
        this.labelShareSize.Name = "labelShareSize";
        this.labelShareSize.Size = new System.Drawing.Size(46, 11);
        this.labelShareSize.TabIndex = 56;
        this.labelShareSize.Tag = "useHeaderImage Core";
        this.labelShareSize.Text = "ShareSize";

由于

1 个答案:

答案 0 :(得分:1)

一种方法可能是在labelName的大小发生变化时调整labelShareSize的位置。以下是使用SizeChanged事件执行此操作的示例代码。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // attach this event handler before the text/size changes
        labelName.SizeChanged += labelName_SizeChanged;

        labelName.Text = "really really really really long text gets set here.........................";
    }

    void labelName_SizeChanged(object sender, EventArgs e)
    {
        AdjustLabelPosition();
    }

    private void AdjustLabelPosition()
    {
        if (labelShareSize.Left < labelName.Location.X + labelName.Width)
            labelShareSize.Left = labelName.Location.X + labelName.Width;
    }
}