Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have Label.Image appear inside the padding region?

Tags:

c#

winforms

I'd like to be able to have a Label such that it appears something like

[Some bit of text here] [ICON]

i.e. the icon follows the text, fairly straightforward.

I don't know what the text will be at design time, so I have AutoSize set to true on the Label control, but this means the image just gets drawn on top of the text. If I add Padding to the right hand side, it doesn't behave as I want (a la CSS, where background images are drawn inside the padding region). Is it possible to do this in C# Winforms? Or am I going to have to measure the text and then change the control width myself?

Thanks.

EDIT: Just to be clear, I wasn't proposing two controls, one after the other. Rather, setting the Label.Image property and have it appear to one side of the label's text. Apparently this is just not built-in functionality for autosized labels which seems pretty weak.

like image 631
Chris Cooper Avatar asked Dec 21 '22 22:12

Chris Cooper


1 Answers

You can do this by deriving your own control from Label and overriding the GetPreferredSize() method. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.

using System;
using System.Drawing;
using System.Windows.Forms;

class MyLabel : Label {
    public MyLabel() {
        this.ImageAlign = ContentAlignment.MiddleLeft;
        this.TextAlign = ContentAlignment.MiddleRight;
    }
    public new Image Image {
        get { return base.Image; }
        set {
            base.Image = value;
            if (this.AutoSize) {  // Force size calculation
                this.AutoSize = false;
                this.AutoSize = true;
            }
        }
    }
    public override Size GetPreferredSize(Size proposedSize) {
        var size = base.GetPreferredSize(proposedSize);
        if (this.Image != null) size = new Size(size.Width + 3 + Image.Width, size.Height);
        return size;
    }
}
like image 150
Hans Passant Avatar answered Dec 24 '22 11:12

Hans Passant