带有换行符的程序化文本块条目

如何以编程方式将带换行符的文本添加到文本块?

如果我插入这样的文字:

helpBlock.Text = "Here is some text.  Here is  some  more."; 

然后,换行符被解释为字符串文字的一部分。 我希望它更像是如果我在XAML中拥有它会发生什么。

我似乎无法用WPF方式做到:

 helpBlock.Inlines.Add("Here is some content."); 

由于Add()方法想要接受“inline”类型的对象。

我无法创建一个Inline对象并将其作为参数传递,因为它由于其保护级别而“无法访问:

 helpBlock.Inlines.Add(new Windows.UI.Xaml.Documents.Inline("More text")); 

我没有看到以编程方式添加运行的方法。

我可以找到大量的WPF示例,但WinRT没有。

我也发现了很多XAML示例,但C#没有。

您可以直接传递换行符\n而不是

 helpBlock.Text = "Here is some text. \n Here is \n some \n more."; 

或者在Xaml中,您将使用换行符的Hex

   

两个结果:

在此处输入图像描述

使用Enviroment.NewLine

 testText.Text = "Testing 123" + Environment.NewLine + "Testing ABC"; StringBuilder builder = new StringBuilder(); builder.Append(Environment.NewLine); builder.Append("Test Text"); builder.Append(Environment.NewLine); builder.Append("Test 2 Text"); testText.Text += builder.ToString(); 

您可以通过编程方式将\n转换为

  string text = "This is a line.\nThis is another line."; IList lines = text.Split(new string[] { @"\n" }, StringSplitOptions.None); TextBlock tb = new TextBlock(); foreach (string line in lines) { tb.Inlines.Add(line); tb.Inlines.Add(new LineBreak()); } 

解:

我会使用“\ n”而不是换行符。 最好的方法是以这种方式使用它:

Resources.resx文件:

 myTextline: "Here is some text. \n Here is \n some \n more." 

在你的class级:

 helpBlock.Text = Resources.myTextline; 

这看起来像:

在此处输入图像描述

其他解决方案是使用Environment.NewLine在此构建您的字符串。

 StringBuilder builder = new StringBuilder(); builder.Append(Environment.NewLine); builder.Append(Resources.line1); builder.Append(Environment.NewLine); builder.Append(Resources.line2); helpBlock.Text += builder.ToString(); 

或者在这里使用“\ n”

 StringBuilder builder = new StringBuilder(); builder.Append("\n"); builder.Append(Resources.line1); builder.Append("\n"); builder.Append(Resources.line2); helpBlock.Text += builder.ToString();