0

我有一个 Windows 窗体,我想从代码隐藏中进行操作。换句话说:

我可以做这样的事情:

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

myForm.TheLableThatIWantToPosition.ForeColor = Color.Red;

etc. 

但是,我怎样才能将它水平定位?我想水平居中。

我尝试过:

myForm.TheLableThatIWantToPosition.TextAlign = ContentAlignment.MiddleCenter;

和所有其他选择,但它只是不会发生。

4

2 回答 2

2

如果您想在标签中居中对齐内容 -

AutoSize = false;
TextAlign = MiddleCenter;
于 2013-08-16T08:10:49.540 回答
1

您可以将此代码放在SizeChanged您的事件处理程序中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;
}

更好的是你应该做这样的事情:

//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.

为了使其动态化,例如,您有一个类CustomLabel,并且您希望它在放置/添加到另一个容器时默认居中:

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;
  }
}
于 2013-08-16T07:59:45.067 回答