How to keep white spaces of TextBlock in UWP applications

If you just set the value of the Text property in the TextBlock as β€œ Example ” (note that there are 3 spaces at the end of this line), which shows the TextBlock in the user interface is just β€œ Example ”.

And after searching for solutions on the Internet, I found that there is a way to solve this problem:

<Border BorderThickness="1" BorderBrush="#FFFF0202" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock x:Name="t1"> <Run Text="Example&#160;&#160;&#160;"/> </TextBlock> </Border> 

The above code shows that using Inline Property TextBlock and &#160; in Run Text displays spaces correctly.

However, I need to set the value of the TextBlock property to Code-behind (or via DataBinding) , the trick above does not work, and it shows Example&#160;&#160;&#160; in the user interface.

I tried to set the value of the Run Text property by data binding, which, I think, can correctly display an escape character, but the Run Text property is NOT a dependent property, so I have no better way to solve this problem.

(However, I think that using the padding property for TextBlock is also a trick for this, and it should work. But is there a better way to do this?)

+6
source share
3 answers

First, Run.Text supports data binding.

The reason &#160; printed incorrectly inside a data binding, is that it uses XML escape characters.

Try using (char)160 instead -

 public string TestString { get; set; } = "Example" + (char)160 + (char)160 + (char)160; <TextBlock> <Run Text="{x:Bind TestString}" /> </TextBlock> 
+6
source

You can try setting the xml:space property to save in XAML

 <TextBox Name="t1" xml:space="preserve" Text="Example " /> 
+1
source

I have a solution for Listview.ItemTemplate in UWP.

 <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock xml:space="preserve"><Run Text="{Binding ID}"></Run><Run> </Run><Run Text="{Binding name}"></Run><Run> </Run><Run Text="{Binding ipAdress}"></Run></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> 
  • Note that the text block has the xml: space = "preserve" attribute.
  • Spaces are set using the <Run> </Run> launch elements.
  • With this solution, you must make sure that the elements and and are defined on the same line in the code editor, otherwise the free space contained in them will be occupied.
0
source

All Articles