You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms Android重建后 空格不加载问题求解决方案

你遇到的 全量编译后失效的问题,是XAMLC(XAML编译)在全量编译阶段会对XAML节点的文本内容做二次转义处理,导致Unicode空格编码被当成普通空白裁剪掉了,Hot Reload阶段不会触发这个二次处理所以显示正常,可通过以下方案解决:

解决方案

方案1:调整空格的放置位置(最简便,无需修改其他配置)

XAML解析器仅会裁剪标签尾部的空白字符,放在标签开头的空格不会被处理,你可以把原来放在前一个Span末尾的空格移到后一个Span的开头,代码如下:

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span TextColor="red">This sentence contains</Span>
            <Span FontAttributes="Bold"> a whole lot of</Span>
            <Span TextDecorations="Underline"> formatted strings!</Span>
        </FormattedString>
    </Label.FormattedText>
</Label>

这个方案无需使用Unicode空格编码,也不需要额外配置,全量编译后空格也能正常保留。

方案2:在后台代码中构造FormattedString

如果需要更灵活的空格控制,可以避开XAML解析器的预处理逻辑,直接在C#代码中生成格式化文本:

var label = new Label();
label.FormattedText = new FormattedString();
label.FormattedText.Spans.Add(new Span { TextColor = Color.Red, Text = "This sentence contains " });
label.FormattedText.Spans.Add(new Span { FontAttributes = FontAttributes.Bold, Text = "a whole lot of " });
label.FormattedText.Spans.Add(new Span { TextDecorations = TextDecorations.Underline, Text = "formatted strings!" });

代码中直接写的普通空格不会被编译逻辑裁剪,稳定性最高。

方案3:给单个Span添加xml:space属性

你之前全局加xml:space="preserve"引发错误的原因是这个属性会影响整个节点下所有空白的解析逻辑,仅给需要保留尾部空格的Span单独添加该属性即可,不会引发额外问题:

<Span TextColor="red" xml:space="preserve">This sentence contains </Span>

方案4:使用资源文件存储文本

如果需要做多语言适配,也可以把带空格的文本存到Strings.resx资源文件中,XAML中绑定资源字符串即可,资源文件中的空格不会被XAML解析器裁剪。

内容的提问来源于stack exchange,提问作者Solus Bellator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:48:04