如何防止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
相关产品推荐
相关产品推荐

