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

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

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

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

当前回答

也许有人更喜欢

<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”。

其他回答

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

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

<TextBlock Text="Stuff on line1&#x0a;Stuff on line 2"/>

您可以使用任何十六进制编码的值来表示文字。在本例中,我使用换行(char 10)。如果你想做“经典的”vbCrLf,那么你可以使用&#x0d;&#x0a;

顺便说一下,请注意语法:它是&号,一个磅,字母x,然后是你想要的字符的十六进制值,最后是一个分号。

此外:为了完整起见,您可以绑定到已经嵌入换行符的文本,就像后面代码中的常量或运行时构造的变量一样。

也许你可以使用属性xml:space="preserve"来保存源XAML中的空白

<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>

你只需要删除<TextBlock。文本>,并简单地添加您的内容如下:

    <Grid Margin="20">
        <TextBlock TextWrapping="Wrap" TextAlignment="Justify" FontSize="17">
        <Bold FontFamily="Segoe UI Light" FontSize="70">I.R. Iran</Bold><LineBreak/>
        <Span FontSize="35">I</Span>ran or Persia, officially the <Italic>Islamic Republic of Iran</Italic>, 
        is a country in Western Asia. The country is bordered on the 
        north by Armenia, Azerbaijan and Turkmenistan, with Kazakhstan and Russia 
        to the north across the Caspian Sea.<LineBreak/>
        <Span FontSize="10">For more information about Iran see <Hyperlink NavigateUri="http://en.WikiPedia.org/wiki/Iran">WikiPedia</Hyperlink></Span>
            <LineBreak/>
            <LineBreak/>
            <Span FontSize="12">
                <Span>Is this page helpful?</Span>
                <Button Content="No"/>
                <Button Content="Yes"/>
            </Span>
    </TextBlock>
    </Grid>

当你需要在字符串中(例如:在你的资源中),你需要使用xml:space="preserve"和&字符代码:

<System:String x:Key="TwoLiner" xml:space="preserve">First line&#10;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个回车符,以及潜在的不可见的尾随空白……