Detect the number of line breaks in TextBlock with wrap? Detect the number of line breaks in TextBlock with wrap? wpf wpf

Detect the number of line breaks in TextBlock with wrap?


You can see how much txtName.ActualHeight you are getting with no wrap, and then divide the ActualHeight (with wrap) by the value you got earlier. You should get the number of lines.

Note: you wont get the Actual height in the constructor. You will get it after the textblock get rendered in the form.

eg:(NoWrap)

txt.ActualHeight311.0

(Wrap)

txt.ActualHeight1420.4400000000019

So,

int lineCount = (txt.ActualHeight / 311.0)

Hope it helps :)

Update as per your question update:

If you need to set messagebox height as per your textblock height, you can simply do this:

msgbox.Height = txt.ActualHeight + 10;

// I added 10 just for adding a little margin.


Windows can adapt their size based on content. See the SizeToContent property.