当文本被设置为属性时,我如何添加换行符:
<TextBlock Text="Stuff on line1 \n Stuff on line2" />
把它分解成分解格式不适合我的特殊情况。我需要的是一些方法来模仿以下:
<TextBlock>
<TextBlock.Text>
Stuff on line1 <LineBreak/>
Stuff on line2
</TextBlock.Text>
<TextBlock/>
当文本被设置为属性时,我如何添加换行符:
<TextBlock Text="Stuff on line1 \n Stuff on line2" />
把它分解成分解格式不适合我的特殊情况。我需要的是一些方法来模仿以下:
<TextBlock>
<TextBlock.Text>
Stuff on line1 <LineBreak/>
Stuff on line2
</TextBlock.Text>
<TextBlock/>
当前回答
<TextBlock>
Stuff on line1 <LineBreak/>
Stuff on line2
</TextBlock>
不是说这是重要的知道,但你指定之间的TextBlock标签被称为内联内容,进入TextBlock。属性,它是一个InlineCollection,包含内联类型的项。 内联的子类包括Run和LineBreak等。 看到TextBlock。内联
其他回答
也不工作
<TextBlock><TextBlock.Text>NO USING ABOVE TECHNIQUE HERE</TextBlock.Text>
没什么大不了的,只是需要用一下
<TextBlock Text="Cool 
Newline trick" />
代替。
解决方案背后的代码
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>Stuff on line1
Stuff on line 2</TextBlock>
当你需要在字符串中(例如:在你的资源中),你需要使用xml:space="preserve"和&字符代码:
<System:String x:Key="TwoLiner" xml:space="preserve">First line Second line</System:String>
或者文本中的换行符:
<System:String x:Key="TwoLiner" xml:space="preserve">First line
Second line</System:String>
警告:如果您编写类似于第二个示例的代码,则您已经插入了换行符,或者回车符和换行符,这取决于您的操作系统和/或文本编辑器使用的行结束符。例如,如果你在linux系统中写了这个代码并提交给git,一切看起来都很好——但如果有人将它克隆到Windows系统中,git会将你的行尾转换为\r\n,这取决于你的字符串是用于…你可能会打破这个世界。
在保留空白时要注意这一点。如果你这样写:
<System:String x:Key="TwoLiner" xml:space="preserve">
First line
Second line
</System:String>
你实际上添加了4个换行符,可能是4个回车符,以及潜在的不可见的尾随空白……
也许有人更喜欢
<TextBlock Text="{Binding StringFormat='Stuff on line1{0}Stuff on line2{0}Stuff on line3',
Source={x:Static s:Environment.NewLine}}" />
xmlns: s =“clr-namespace:系统;装配= mscorlib”。