I want to have a text area that fit the length of text. My XAML is the following:
<Border Name="TextBorder" Margin="10, 0,10,280" >
<TextBlock x:Name="TextArea" TextWrapping="Wrap" Margin="4,0,4,0" TextAlignment="Left" VerticalAlignment="Center">Text to display</TextBlock>
</Border>
I count the number of characters to ind the number of lines :
var txt = TextArea.Text;
var nbOfLetters = txt.Length;
var letterSize = TextArea.FontSize;
var boxWidth = _initialDrawWidth - 2*_lateralSpace; // fixed size
var nbOfLines = (int)( (nbOfLetters * letterSize) / boxWidth + 0.99 ); // (int) + 0.99 --> round to upper value
var calculatedHeight = letterSize * nbOfLines;
Then I set the margin:
TextArea.Margin = new Thickness(_lateralSpace, _topSpace, _lateralSpace, (_initialDrawHeight - _topSpace - calculatedHeight));
But the size doesn't fit. Even the number of line doesn't work, sometimes I have 1 line displayed but the calcul gives 2.
I made a test, with a fontsize of 11, and a a lenght of textarea of 202 I have 31 characters. But 202/31 = 6.5 not 11 ? I don't understand: each value is expressed in the same unit, device independent pixel.
Do you know where I am wrong and how to solve it ?