Right-aligned labels in WinForms

后端 未结 9 1447
甜味超标
甜味超标 2021-01-07 15:59

The most obvious way to right-align a Label in WinForms doesn\'t work: setting anchor to Top/Bottom Right and TextAlign to TopRight. If the text changes the lab

9条回答
  •  抹茶落季
    2021-01-07 16:27

    Attach an event handler to the labels' SizeChanged event:

    private void label1_SizeChanged(object sender, EventArgs e)
    {
        label1.Location = new Point(Your_Anchor_Point - label1.Width, label1.Location.Y);
    }
    

    To be more DPI friendly consider using some other control as the anchor point, i.e.

    label1.Location = new Point(dataGridView1.Location.X + dataGridView1.Width - label1.Width, label1.Location.Y);
    

    to align to the RH side of the dgv.

    (BTW: I tried the Paint & TextChanged events but they seemed to sometimes get confused - probably something to do with event order particularly on opening a new form.)

提交回复
热议问题