当文本被设置为属性时,我如何添加换行符:

<TextBlock Text="Stuff on line1 \n Stuff on line2" />

把它分解成分解格式不适合我的特殊情况。我需要的是一些方法来模仿以下:

<TextBlock>
  <TextBlock.Text>
    Stuff on line1 <LineBreak/>
    Stuff on line2
  </TextBlock.Text>
<TextBlock/>

当前回答

解决方案背后的代码

private void Button1_Click(object sender, RoutedEventArgs e)
{
    System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
    myStringBuilder.Append("Orange").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Apple").AppendLine();
    myStringBuilder.Append("Banana").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Plum").AppendLine();
    TextBox1.Text = myStringBuilder.ToString();
}

其他回答

也不工作

<TextBlock><TextBlock.Text>NO USING ABOVE TECHNIQUE HERE</TextBlock.Text>

没什么大不了的,只是需要用一下

<TextBlock Text="Cool &#x0a;Newline trick" />

代替。

注意,要做到这一点,你需要在文本属性中这样做,你不能使用像这样的内容

<TextBlock>Stuff on line1&#x0a;Stuff on line 2</TextBlock>
<TextBlock>
    Stuff on line1 <LineBreak/>
    Stuff on line2
</TextBlock>

不是说这是重要的知道,但你指定之间的TextBlock标签被称为内联内容,进入TextBlock。属性,它是一个InlineCollection,包含内联类型的项。 内联的子类包括Run和LineBreak等。 看到TextBlock。内联

解决方案背后的代码

private void Button1_Click(object sender, RoutedEventArgs e)
{
    System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
    myStringBuilder.Append("Orange").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Apple").AppendLine();
    myStringBuilder.Append("Banana").AppendLine();
    myStringBuilder.Append("").AppendLine();
    myStringBuilder.Append("Plum").AppendLine();
    TextBox1.Text = myStringBuilder.ToString();
}

我知道这是一个老问题,但我只是想补充一下

环境。换行符

如果通过代码来做这个也可以。