Label.Image是否可以出现在填充区域内?

Chr*_*per 4 c# winforms

我希望能够有Label这样的东西

[这里的一些文字] [ICON]

即图标跟随文本,相当简单.

我不知道文本在设计时会是什么,所以我AutoSizeLabel控件上设置为true ,但这意味着图像只是在文本的顶部绘制.如果我添加Padding到右侧,它不会像我想要的那样(一个CSS,在填充区域内绘制背景图像).是否可以在C#Winforms中执行此操作?或者我将不得不测量文本然后自己更改控制宽度?

谢谢.

编辑:为了清楚起见,我没有提出两个控制,一个接一个.而是设置Label.Image属性并使其显示在标签文本的一侧.显然,这不是自动标签的内置功能,看起来相当弱.

Han*_*ant 6

您可以通过从Label派生自己的控件并覆盖GetPreferredSize()方法来完成此操作.在项目中添加一个新类并粘贴下面显示的代码.编译.将新控件从工具箱顶部拖放到表单上.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)