Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make wpf textblock autosize

Tags:

c#

wpf

i have a textblock where i dynamically add string.. even if i add string width and update the textblock the textblock is not showing appropriate width, still some text are cut..

how to measure width that has to be displayed in textblock? and how to make it autosize?

like image 848
curiosity Avatar asked Sep 24 '10 04:09

curiosity


1 Answers

You can get the size of a text using these solutions :

Solution 1

You could FormattedText to measure the size of text, here is an example:

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);

Solution 2

Use the Graphics class (found 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);

Here you are !

like image 170
Jonathan ANTOINE Avatar answered Sep 30 '22 19:09

Jonathan ANTOINE