如何在 UWP 应用中保留 TextBlock 的空格 [英] How to preserve white-spaces of TextBlock in UWP apps
问题描述
如果您只是将 TextBlock 中 Text 属性的值设置为示例"(请注意,此字符串的末尾有 3 个空格),TextBlock 显示的内容在 UI 中只是示例".
If you simply set the value of Text property in a TextBlock as "Example " (Note that there 3 whitespaces at the end of this string),what TextBlock shows in UI is just "Example".
然后在网上搜索了解决方案,发现有一个方法可以解决这个问题:
And after searching for solutions on the Internet, I found that there is a way to solve this issue:
<Border BorderThickness="1"
BorderBrush="#FFFF0202"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<TextBlock x:Name="t1">
<Run Text="Example   "/>
</TextBlock>
</Border>
上面的代码显示了使用 TextBlock 的 Inline 属性和  
在 Run 的 Text 中正确显示空格.
The above code shows the use of Inline Property of TextBlock and  
in Run's Text displays the whitespace correctly.
但是,我的情况是我需要在代码隐藏(或通过数据绑定)中设置 TextBlock 的 Text 属性,上面的技巧不起作用,它显示 用户界面中的示例   
.
However, im my case I need to set the Text property of TextBlock in Code-behind(or via DataBinding), the trick above doesn't work and it shows Example   
in UI.
我试图通过数据绑定设置 Run 的 Text 属性的值,我认为这可以正确显示转义字符,但 Run 的 Text 属性不是依赖属性,所以我没有更好的方法来解决这个问题.
I tried to set the value of Run's Text property by data binding, which I think can displays the escape character correctly, but Run's Text property is NOT a dependency property so I have no better way to solve this.
(不过我认为使用 TextBlock 的 padding 属性也是一个技巧,它应该可以工作.但是有更好的方法吗?)
(However I think use padding property of TextBlock is also a trick to do this, and it should work. But there is any better way to do ?)
推荐答案
首先,Run.Text
确实支持数据绑定.
First, Run.Text
does support data binding.
 
在数据绑定中无法正确打印的原因是它使用了 XML 转义字符.
The reason that  
doesn't print correctly inside data binding is because it's using XML escape characters.
尝试使用 (char)160
代替 -
public string TestString { get; set; } = "Example" + (char)160 + (char)160 + (char)160;
<TextBlock>
<Run Text="{x:Bind TestString}" />
</TextBlock>
这篇关于如何在 UWP 应用中保留 TextBlock 的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!