【问题标题】:How to set height of textblock/textbox to 3 lines?如何将文本块/文本框的高度设置为 3 行?
【发布时间】:2016-01-15 04:09:13
【问题描述】:

我可以以像素为单位设置固定高度,但我想将其设置为行。有点像在 html 中,您可以将 textarea 的高度设置为行数/行数。

【问题讨论】:

    标签: wpf textblock


    【解决方案1】:

    对于文本框,设置 MinLines 和 MaxLines 属性。为了更好地接近 HTML 文本区域,还可以考虑设置 TextWrapping、VerticalScrollBarVisibility 和 AcceptsReturn,如下所示:

    <TextBox TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True" MinLines="3" MaxLines="3"/>
    

    【讨论】:

    • Min lines 设置您将始终看到的最少行数,Max lines 是显示的最大行数,然后激活滚动条以查看其他行。
    【解决方案2】:

    解决方案 1

    你可以用 FormattedText 来测量文本的大小,这里是一个例子:

    String text = "Here is my text";
    Typeface myTypeface = new Typeface("Helvetica");
    FormattedText ft = new FormattedText(text, CultureInfo.CurrentCulture, 
            FlowDirection.LeftToRight, myTypeface, 16, Brushes.Red);
    
    Size textSize = new Size(ft.Width, ft.Height);
    

    解决方案 2

    使用 Graphics 类(找到 here):

    System.Drawing.Font font = new System.Drawing.Font("Calibri", 12, FontStyle.Bold);
    Bitmap bitmap = new Bitmap(1, 1);
    Graphics g = Graphics.FromImage(bitmap);
    SizeF measureString = g.MeasureString(text, font);
    

    你来了!

    【讨论】:

      【解决方案3】:

      试试3em

      1em 等于当前字体大小。 2em 表示当前字体大小的 2 倍。例如,如果一个元素以 12 pt 的字体显示,那么 '2em' 就是 24 pt。

      【讨论】:

      • 这是否考虑了前导(WPF 称之为 LineHeight、iirc)?如果没有,那么您的行数可能少于三行。
      • 根据 MSDN 只允许 px、in、cm、pt,不允许使用 em
      • 也许你可以以某种方式转换它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多