您可以将此代码放在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;
}
}