c# - 具有自动高度属性的用户控件

标签 c# .net winforms user-controls windows-forms-designer

我想创建将显示文本的用户控件。
我需要一种在运行时调整控件大小的方法,以便它调整高度以显示所有文本。 我创建了如下所示的控件:

enter image description here

如您所见,我使用 TextRenderer.DrawText 绘制了图标和文本。不幸的是,当我调整控件大小(仅向左或向右)时,我的文本有时会被剪切,如下所示:

enter image description here

我正在使用 TextRenderer.MeasureText 测量文本,基于此我正在计算行数,然后绘制该文本。这是我正在使用的代码:

[Designer(typeof(MyTextBoxDesigner))]
public partial class MyTextBox : UserControl
{
    public MyTextBox()
    {
        InitializeComponent();
    }

    [DefaultValue("Demo"), Description("Text of control"), Category("Appearance"),Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            if (base.Text == value) return;
            base.Text = value;
            Invalidate();
        }
    }

    Image _image;
    [Description("Image shown on the left side of the control"),
    Category("Appearance")]
    public Image Image
    {
        get
        {
            return _image;
        }
        set
        {
            if (_image == value) return;
            _image = value;
            Invalidate();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        int imagePadding = 0;
        if (_image != null)
        {
            imagePadding = 25;
            e.Graphics.DrawImage(_image,new Rectangle(5,5,16,16));
        }
        Size textSize1 = TextRenderer.MeasureText(e.Graphics, Text, Font);
        SizeF textSize2 = e.Graphics.MeasureString(Text, Font);

        Debug.WriteLine(textSize2);

        int maxTextWidth = Width - Padding.Left-Padding.Right-imagePadding;
        int lineHeight = textSize1.Height + 2;
        int numLines = 1;

        if (textSize1.Width > maxTextWidth)
        {
            numLines = textSize1.Width / maxTextWidth + 1;
        }

        Rectangle textRect = new Rectangle
        {
            Width = Width - Padding.Left-Padding.Right-imagePadding,
            Height = (numLines * lineHeight),
            X = Padding.Left+imagePadding,
            Y = 5
        };

        TextRenderer.DrawText(e.Graphics, Text, Font, textRect, ForeColor, TextFormatFlags.WordBreak | TextFormatFlags.Left | TextFormatFlags.Top);

        e.Graphics.DrawRectangle(Pens.CadetBlue, textRect);

        base.OnPaint(e);
    }
}

internal class MyTextBoxDesigner : ControlDesigner
{
    public override SelectionRules SelectionRules
    {
        get
        {
            //all minus bottom and top
            return (base.SelectionRules & ~(SelectionRules.BottomSizeable | SelectionRules.TopSizeable));
        }
    }
}

理想情况下,我希望我的控件能够根据文本长度自动调整高度,因此如果文本很短(或控件足够长),则高度将是例如 20px,但如果文本很长,我的控件应该是(例如示例)40px 高度(2 行文本)。

我应该如何更改文本测量以正确计算 textRect
我应该使用 Size 属性更新控件的高度还是有更好的方法?

编辑: 基本上我想绘制可以包裹在矩形内的文本,但具有固定的宽度,因此当文本较长时,矩形将调整其高度。然后根据该高度我想调整控件高度。

最佳答案

这是一个自动高度控件。如果更改控件的宽度,控件的高度也会发生变化,从而可以显示整个文本。

enter image description here

您可以使用不同的方法创建此类控件,包括:

  • 方法 1:自动调整托管标签的复合控件的大小
    此方法基于托管自动大小 Label在自动调整大小时具有动态最大宽度 Control 。在这种方法中,我们根据控件的宽度设置标签的最大宽度,并且由于标签是自动调整大小的,因此它的高度将自动设置为显示所有文本,然后我们根据标签的高度设置控件的高度。

  • 方法 2:从头开始自动调整大小,无需标签
    此方法基于重写 SetBoundsCore 并根据其Text设置控件的大小尺寸。在这种方法中,我们使用 TextRenderer.MeasureText 根据控件的宽度计算文本的大小。然后将计算出的高度设置为控件的高度。在这种方法中,您应该自己处理文本格式标志并进行渲染。

在这两种方法中 ControlDesigner用于禁用除左和右之外的所有尺寸 handle 。

请注意

这些并不是唯一可用的方法,但却是很好的例子。作为另一个选项,您可以继承 Label并改变它的行为。

方法 1:自动调整托管标签的复合控件的大小

它基于设置 AutoSize 工作标签属性为true然后设置MaximumSize基于控件的标签Width 。控件的高度也是根据标签的高度设置的。 您可以简单地在 OnPaint 中绘制图像方法。您还可以添加 PictureBox对于图像。

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
[Designer(typeof(MyLabelDesigner))]
public partial class MyLabel : Control
{
    public MyLabel() { InitializeComponent(); }
    private System.Windows.Forms.Label textLabel;
    private void InitializeComponent()
    {
        this.textLabel = new System.Windows.Forms.Label();
        this.textLabel.AutoSize = true;
        this.textLabel.Location = new System.Drawing.Point(0, 0);
        this.textLabel.Name = "label1";
        textLabel.SizeChanged += new EventHandler(textLabel_SizeChanged);
        this.AutoSize = true;
        this.Controls.Add(this.textLabel);
    }
    void textLabel_SizeChanged(object sender, EventArgs e)
    {
        this.Height = this.textLabel.Bottom + 0;
    }
    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        this.textLabel.MaximumSize = new Size(this.Width, 0);
    }
    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override string Text
    {
        get { return this.textLabel.Text; }
        set { this.textLabel.Text = value; }
    }
}

方法 2:从头开始自动调整大小,无需标签

此方法的工作原理是基于 SetBoundsCore 中设置控件大小。基于当前宽度和计算出的高度 Text 。计算控制高度。您可以简单地画Image .

using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms.Design;
[Designer(typeof(MyLabelDesigner))]
public class ExLabel : Control
{
    public ExLabel()
    {
        AutoSize = true;
        DoubleBuffered = true;
        SetStyle(ControlStyles.ResizeRedraw, true);
    }
    protected override void OnTextChanged(System.EventArgs e)
    {
        base.OnTextChanged(e);
        SetBoundsCore(Left, Top, Width, Height, BoundsSpecified.Size);
        Invalidate();
    }
    protected override void SetBoundsCore(int x, int y, int width, int height,
        BoundsSpecified specified)
    {
        var flags = TextFormatFlags.Left | TextFormatFlags.WordBreak;
        var proposedSize = new Size(width, int.MaxValue);
        var size = TextRenderer.MeasureText(Text, Font, proposedSize, flags);
        height = size.Height;
        base.SetBoundsCore(x, y, width, height, specified);
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        var flags = TextFormatFlags.Left | TextFormatFlags.WordBreak;
        TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle,
            ForeColor, BackColor, flags);
    }
}

设计师

这是 ControlDesigner用于将设计器中的 handle 大小限制为左侧和右侧的两种实现:

using System.Windows.Forms.Design;
public class MyLabelDesigner : ControlDesigner
{
    public override SelectionRules SelectionRules
    {
        get
        {
            return (base.SelectionRules & ~(SelectionRules.BottomSizeable | 
                                            SelectionRules.TopSizeable));
        }
    }
}

关于c# - 具有自动高度属性的用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38203411/

相关文章:

c# - 为什么我的 IOCompetionCallback 从未在我的 IO 完成端口上执行?

c# - 将任何日期时间值转换为 UTC

c# - WCF 服务引用 - 在客户端获取 "XmlException: Name cannot begin with the ' <' character, hexadecimal value 0x3C"

.net - Winforms 文本框粘贴不可靠?

c# - "s"作为格式说明符有什么作用?

c# - 从包装 native C++ 类的 CLI 类调用 C# 委托(delegate)

.net - 使用 Javascript .NET 回发传递多个参数

c# - 具有调整框架大小但没有标题栏的 Windows 窗体?

c# - 如何动态获取文本框中datagridview列的总和

c# - 在 C# 中比较字符串和字符