我可以设置固定高度(以像素为单位),但我希望按行数设置高度。有点像在 HTML 中,你可以将文本区域的高度设置为行数。
对于TextBox,请设置MinLines和MaxLines属性。如果要更好地近似HTML文本区域,请考虑按以下方式设置TextWrapping、VerticalScrollBarVisibility和AcceptsReturn:
<TextBox TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True" MinLines="3" MaxLines="3"/>
您可以使用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);
使用Graphics类(在此处找到):
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);
Here you are !
尝试使用3em
1em等于当前字体大小。2em表示当前字体大小的两倍。例如,如果一个元素以12pt的字体显示,则'2em'为24pt。