0

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 ?

Freddlow
  • 167
  • 1
  • 12
  • 1
    Unless you’re using a monospace font all characters take different amount. Font size is the height, not the width, and it’s not necessarily a pixel size even then. – Sami Kuhmonen Jun 03 '18 at 13:21
  • @Sami Kuhmonen OK, that is why the behavior is not constant. Do you have an idea to calculate the real length of the total string ? – Freddlow Jun 03 '18 at 13:24
  • Duplicate: https://stackoverflow.com/q/9264398/17034 – Hans Passant Jun 03 '18 at 13:42

0 Answers0