简体   繁体   中英

Windows Forms label custom control origin change

I have a custom control derived from a label. I need to change the native control's location origin from upper left to lower left.

Is there a method or property to do this?

The TextAlign property should do what you need.

label.TextAlign = System.Drawing.ContentAlignment.BottomLeft;

If you're trying to make the Location property reflect the bottom-right corner of the control rather than the top-left, then this isn't possible. You can, however, create your own property:

public Point BottomLeft
{
    get { return new Point(Left, Bottom); }
    set { Location = new Point(value.X, value.Y - Height); }
}

Bear in mind, though, that this won't remain true if the Height property changes (you'll have to set it again).

If you want to change the behavior of the Label.Location property so that it refers to the bottom-left corner of the label, you could override InitLayout() in your custom label:

class myLabel : Label
{
    protected override void InitLayout()
    {
        base.InitLayout();
        Location = new Point(Location.X, Location.Y - Height);                
    }
}

This will shift the control up based on the height of the control. So if you start with (100,100) and the label height is 13, you will end with (100,87), which puts the bottom-left corner at (100,100).

But this will only happen when the label is added to a container. If you change the Location of the label after adding it to a container, it will go back to the top-right corner.

The other thing you might try is overriding LayoutEngine { get; } LayoutEngine { get; } of the container which the label is in, so that you have full control over how the Location property of any custom label placed in the container is interpreted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM