You need to enable JavaScript to run this app. 如何防止XAML中Editor.Text的代码换行被Xamarin识别为硬换行
优惠活动
大模型
产品
解决方案
定价
更多

如何防止XAML中Editor.Text的代码换行被Xamarin识别为硬换行

方案1:使用xml:space属性(最简便)

XAML默认对元素内部文本启用xml:space="preserve"规则,会保留所有换行、缩进等空白字符。你只需要给Editor控件显式指定xml:space="default",解析器就会自动把连续的空白(包括换行、多个空格、制表符)合并为单个空格,最终展示效果和写在同一行完全一致。
代码示例:

<Editor IsReadOnly="True" xml:space="default">
    <Editor.Text>
        This is a lot of text.
        So much text that I want to break it onto two or more lines in my XAML.
    </Editor.Text>
</Editor>

方案2:后台代码赋值

如果你不想修改XAML的空白处理规则,可以在后台代码中给Text属性赋值,C#的多行原始字符串可以自由换行,再通过替换操作去掉换行符:

// 页面构造函数中
editor.Text = @"This is a lot of text.
So much text that I want to break it onto two or more lines in my XAML."
.Replace(Environment.NewLine, " ").Trim();

方案3:自定义标记扩展(适合高频使用场景)

如果项目中经常有这类需求,可以实现一个简单的XAML标记扩展,自动处理多行文本的空白合并:
首先定义扩展类:

using System;
using Xamarin.Forms;
using System.Text.RegularExpressions;

[ContentProperty(nameof(Text))]
public class MergeWhitespaceExtension : IMarkupExtension<string>
{
    public string Text { get; set; }

    public string ProvideValue(IServiceProvider serviceProvider)
    {
        return string.IsNullOrEmpty(Text) ? 
            string.Empty : 
            Regex.Replace(Text, @"\s+", " ").Trim();
    }

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return ProvideValue(serviceProvider);
    }
}

XAML中使用:

<Editor IsReadOnly="True">
    <Editor.Text>
        <local:MergeWhitespace>
            This is a lot of text.
            So much text that I want to break it onto two or more lines in my XAML.
        </local:MergeWhitespace>
    </Editor.Text>
</Editor>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 17:57:02