如何在 UWP 应用中保留 TextBlock 的空白

2

本文介绍了如何在 UWP 应用中保留 TextBlock 的空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果您只是将 TextBlock 中的 Text 属性的值设置为示例 "(请注意,此字符串的 end 处有 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&#160;&#160;&#160;"/>
    </TextBlock>
</Border>

以上代码展示了TextBlock的Inline属性的使用,&#160;在Run的Text中正确显示了空白.

The above code shows the use of Inline Property of TextBlock and &#160; in Run's Text displays the whitespace correctly.

但是,在我的情况下,我需要在 Code-behind(或通过 DataBinding) 中设置 TextBlock 的 Text 属性,上面的技巧不起作用,它显示 UI 中的示例&#160;&#160;&#160;.

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&#160;&#160;&#160; 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.

&#160; 在数据绑定中无法正确打印的原因是它使用了 XML 转义字符.

The reason that &#160; 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 的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14