My solution is as follows:
Set the fontsize value to a value that you no longer need. The ActualHeight value for the TextBlock changes when the font size changes or when the content changes. I built a solution based on this. You must create an event handler for the SizeChanged event and write the following code into it.
private void MyTextBlock_SizeChanged(object sender, SizeChangedEventArgs e) { double desiredHeight = 80;
The reason I used Math.Sqrt () is because if you set the font size two times larger than before, then the area in which the font will be used will be a quarter smaller, and then (since this became half wide and half high as before). And you clearly want to keep the width of the TextBox and only change its height.
If you're lucky, the font size will be appropriate after this method is executed once. However, depending on the text that will be repackaged after changing the font size, you may be so lucky that the text will be one line longer than you would like. Fortunately, the event handler will be called again (because you changed the font size), and the resizing will be performed again if it is still too large.
I tried, it was fast, and the results looked good. However, I can imagine that in a really bad choice of text and height, the correct font size will be achieved after several iterations. This is why I used Math.Floor (). All in all, it doesn't really matter if the font size is at the end of 12.34 or 12, and so I wonโt worry about โunluckyโ text that will be too long to render. But I think that Math.Floor () can be omitted if you do not want to have a very high text box (e.g. 2000 pixels) with lots of text.
source share