c# - 按文本内容自动调整面板大小

标签 c# .net winforms

我有一个 WinForms 应用程序,我想在其中添加动态停靠到顶部的 UserControls:

this.Controls.Clear();
this.Controls.Add(myCustomControl(){Title="first", content="first text", Dock=DockStyle.Top});
this.Controls.Add(myCustomControl(){Title="second", content="very long text, where......", Dock=DockStyle.Top});

现在 myCostumControl [YELLOW] 是一个包含以下内容的 userControl:

TopTitle [PINK]: A Label, docked to the top
BottomContent [GREEN]: A Panel, Fills out the rest of the Control below the TopTitle (Dockstyle Fill)
TextContent [BLUE]: A multiline Textbox, docked (fill) within the Panel.

所以看起来像这样:

enter image description here

现在我需要实现的是 myCustomControl 的高度根据“TextContent”-TextBox 的文本内容,因此我可以堆叠多个控件。所以如果里面只有一个“Hello World”,高度应该很小,如果我把 Windows EULA 放在里面它应该很长。

我已经尝试弄乱所有我能得到的“AutoSize”属性,但文本框要么完全消失,要么没有任何效果。

我还尝试在更改时调整文本框的大小:

Size size = TextRenderer.MeasureText(txtContent.Text, txtContent.Font);
txtContent.Height = size.Height; 

也没有成功

最佳答案

要使复合控件自动调整大小,请执行以下设置:

  • 在用户控件中添加一个Label,将label的AutoSize设置为false,将其高度设置为合适的高度,并将其Dock设置为顶。
  • 向用户控件添加一个 TextBox 并将其 Dock 设置为 Fill
  • 覆盖 SetBoundsCore 并计算控件的首选大小:

    protected override void SetBoundsCore(int x, int y, int width, int height,
        BoundsSpecified specified)
    {
        var flags = TextFormatFlags.WordBreak | TextFormatFlags.NoPrefix;
        var proposedSize = new Size(width, int.MaxValue);
        var size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font,
            proposedSize, flags);
        height = Math.Max(size.Height, textBox1.Font.Height) + label1.Height + 5;
        base.SetBoundsCore(x, y, width, height, specified);
    }
    
  • 处理 TextBoxTextChanged 事件以在内容文本更改时刷新控件的大小:

    void textBox1_TextChanged(object sender, EventArgs e)
    {
        SetBoundsCore(Left, Top, Width, Height, BoundsSpecified.Size);
    }
    

结果如下:

enter image description here

关于c# - 按文本内容自动调整面板大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385206/

相关文章:

c# - 如何使用按钮单击在特定文本框中输入文本

C# 设计 View 不会在 winform 中加载图形元素

c# - 持续引用的最佳方法或替代方案是什么?

c# - 有什么方法可以在没有 "/Rect"的情况下获得 AcroField 在 PdfSharp 中的位置?

c# - 使用paint时如何在WinForms中实现垂直和水平滚动条?

c# - 项目引用解决方案 .net 4.5 和 .net 3.5

c# - 在 C# .NET Core 的断言有效负载中使用自定义数据为第 3 方应用程序创建 SAML 断言

C# LINQ 多选

.net - Visual Studio 2010 插件撰写文章/教程?

vb.net - 如何在 DataGridView 的列中居中标题?