【问题标题】:Adapt the height of a TextBox调整文本框的高度
【发布时间】:2018-07-04 10:37:31
【问题描述】:

我正在开发一个包含多行文本框的用户控件。

使用我的控件时,可以设置要显示的文本。然后 TextBox 应该调整其高度以使文本适合,宽度不能改变。

所以这里是处理文本的属性:

[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
public string TextToDisplay
{
    get
    {
        return internalTextBox.Text;
    }
    set
    {
        internalTextBox.Text = value;
        AdaptTextBoxSize();
    }
}

我的第一次尝试相当简单:

private void AdaptTextBoxSize()
{
    int nbLignes = internalTextBox.Lines.Length;
    float lineHeight = internalTextBox.Font.GetHeight();
    internalTextBox.Height = (int)((nbLignes) * lineHeight);
}

这不起作用,因为它没有考虑两行文本之间的间距。所以我在文本中的行越多,我被剪掉的越多。

所以我尝试了这个:

private void AdaptTextBoxSize()
{
    Size textSize = internalTextBox.GetPreferredSize(new Size(internalTextBox.Width, 0));
    internalTextBox.Height = textSize.Height;
}

当文本框中的所有行都短于宽度时,这确实有效。但是当一行较长并且应该剪裁到下一行时,GetPreferredSize() 返回的宽度比我传递的要大,因此高度太小了。

于是我又换了一个,试了这个:

private void AdaptTextBoxSize()
{
    Size textSize = TextRenderer.MeasureText(
                                             internalTextBox.Text, 
                                             internalTextBox.Font, 
                                             new Size(internalTextBox.Width, 0), 
                                             TextFormatFlags.WordEllipsis
                                             );


    internalTextBox.Height = textSize.Height;
}

这次返回的Width是正确的,因为它没有超过我通过的那个,但是高度和之前试的一样。所以它也不起作用。我为TextFormatFlags 尝试了不同的组合,但无法找到获胜的组合...

这是来自框架的错误吗?

这里真正的问题是,我是否可以尝试另一件事,或者另一件事来实现我想要的(即在设置 TextToDisplay 属性时自动调整高度)?

【问题讨论】:

  • UseCompatibleTextRendering 属性的值是多少? This 可能是相关的。
  • @AhmedAbdelhameed 好吧,我尝试了您链接中的解决方案,但仍然遇到同样的问题。这些值略有不同,但如果我的一条线太长,我仍然有一条线被剪掉。
  • 你为什么使用TextFormatFlags.WordEllipsis?试试simpler solution。衡量文本是正确的方法(无需质疑整个故事),它应该有效。我建议您仅发布带有测量文本尝试和有问题的屏幕截图的代码。 “高度与之前的试验相同” 可能是一个有趣但不是真正有用的观察。
  • 宽度存在已知问题:herehere。尝试使用TextFormatFlags.WordBreak(来自here),结果会不同吗?
  • @Sinatr 我实际上没有问题测量宽度,但测量高度。我的宽度是固定的,但是当一条线太长时,计算出的高度似乎不正确。我会更新我的问题

标签: c# winforms autosize


【解决方案1】:

TextBox.GetPositionFromCharIndex 返回字符的像素位置。 Position 这里的意思是top/left,所以我们需要多加一行..

这似乎在这里工作:

textBox.Height = textBox.GetPositionFromCharIndex(textBox4.Text.Length - 1).Y + lineHeight;

我得到这样的行高:

int lineHeight = -1;
using (TextBox t = new TextBox() { Font = textBox.Font }) lineHeight = t.Height;

我设置了Height 而不是ClientSize.Height,这有点错误,除非BorderStyleNone。你可以换成textBox.ClientSize = new Size(textBox.ClientSize.Width, l + lh);

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2014-09-30
    • 2012-05-21
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    相关资源
    最近更新 更多