Search code examples
c#.netwpfxamlwpf-textbox

WPF TextBox and spaces


I create a string from multiple fields that has leading blanks/spaces suing StringBuilder.

When I export it to text file or even insert one by one to WPF TextBox and after this copy and paste to Notepad.exe or Notepad++.exe I see the perfect aligned fields and that is ok because of the leading blanks.

But visually in WPF TextBox (as well as in WPF TextBlock and WPF RichTextBox) it gets messing. Take a look at the screemshot below at the top you see TextBox and below a Notepad++.

Any clue why does WPF TextBox not align characters well? Can we manage it?

enter image description here

XAML

 <TextBox x:Name="TbOutputFile"  IsReadOnly="True"   Foreground="Green" HorizontalAlignment="Stretch"  TextWrapping="NoWrap" HorizontalScrollBarVisibility="Visible"  VerticalScrollBarVisibility="Visible" />

Solution

  • You need to use a mono space font line Consolas. In most fonts all characters are not the same width. This will cause things to get out of alignment. It a text box it is using a monospace font. Here is a list of sone of them. https://www.google.com/search?q=monospace+font+list&ie=utf-8&oe=utf-8

    Or you can use tab characters in a richtext box.