当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to position a Label horizontally in Windows Forms code-behind

问题描述:

I have a Windows form that I want to manipulate from code-behind.In other words:

I can do stuff like this:

myForm.TheLableThatIWantToPosition.Text = "Some text!";

myForm.TheLableThatIWantToPosition.ForeColor = Color.Red;

etc.

But, how can I position it horizotnally ? I want to center it horizontally.

I tried with the:

myForm.TheLableThatIWantToPosition.TextAlign = ContentAlignment.MiddleCenter;

and all the other options but it just doesn't happen.

网友答案:

If you want to center align content in label -

AutoSize = false;
TextAlign = MiddleCenter;
网友答案:

You can place this code in a SizeChanged event handler of your label1.Parent:

if(label1.Parent != null){ //this if check may be removed if it's sure that Parent is not null
 label1.Left = (label1.Parent.Width - label1.Width)/2;
}

Better you should do something like this:

//SizeChanged event handler for your label1
private void label1_SizeChanged(object sender, EventArgs e){
   label1.Left = (label1.Parent.Width - label1.Width)/2;
}
//SizeChanged event handler for your label1's Parent
private void parent_SizeChanged(object sender, EventArgs e){
   label1.Left = (label1.Parent.Width - label1.Width)/2;
}
//you can change label1.Parent with a control reference which you know it's the container of your label1.

To make it dynamically, for example you have a class CustomLabel and you want it to be centered by default whenever it's placed/added to another container:

public class CustomLabel : Label {
  public CustomLabel(){
     IsCentered = true;
  }
  private Control oldParent;
  public bool IsCentered {get;set;}//You can define an Enum if needed
  protected override void OnSizeChanged(EventArgs e){
    if(Parent != null&&IsCentered){
       Center();
    }
  }
  protected override void OnParentChanged(EventArgs e){
     if(Parent != null){
        if(oldParent != null) oldParent.SizedChanged -= parent_SizeChanged;
        Parent.SizedChanged -= parent_SizeChanged;
        Parent.SizedChanged += parent_SizeChanged;
        Center();
     }
     oldParent = Parent;
  }
  private void parent_SizeChanged(object sender, EventArgs e){
    if(IsCentered) Center();
  }
  public void Center(){
    Left = (Parent.Width - Width)/2;
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: