如何将新行放入 wpf TextBlock 控件中?

发布于 2024-12-21 08:31:46 字数 462 浏览 3 评论 0原文

我正在从 XML 文件中获取文本,并且想插入一些由文本块渲染解释为新行的新行。

我已经尝试过:

<data>Foo bar baz \n baz bar</data>

但数据仍然显示,没有新行。我通过 C# 通过 .Text 属性设置 的内容。

我需要在 XML 中添加什么内容才能在 GUI 中呈现新行?

我已经尝试过类似的方法,在 XAML 中手动设置文本:

<TextBlock Margin="0 15 0 0" Width="600">
There &#10;
is a new line.
</TextBlock>

虽然编码的字符没有出现在 GUI 中,但它也没有给我一个新行。

I'm fetching text from an XML file, and I'd like to insert some new lines that are interpreted by the textblock render as new lines.

I've tried:

<data>Foo bar baz \n baz bar</data>

But the data is still displayed without the new line. I set the contents of <data> via the .Text property via C#.

What do I need to put in the XML in order for it to render the new line in the GUI?

I've tried something like this manually setting the text in the XAML:

<TextBlock Margin="0 15 0 0" Width="600">
There 

is a new line.
</TextBlock>

And while the encoded character doesn't appear in the GUI it also doesn't give me a new line.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

时光倒影 2024-12-28 08:31:46

您可以尝试在数据中添加新行:

<data>Foo bar baz 
 baz bar</data>

如果这不起作用,您可能需要手动解析字符串。

顺便说一下,如果您需要直接 XAML,那很简单:

<TextBlock>
    Lorem <LineBreak/>
    Ipsum
</TextBlock>

You can try putting a new line in the data:

<data>Foo bar baz 
 baz bar</data>

If that does not work you might need to parse the string manually.

If you need direct XAML that's easy by the way:

<TextBlock>
    Lorem <LineBreak/>
    Ipsum
</TextBlock>
一袭白衣梦中忆 2024-12-28 08:31:46

为了完整起见:您还可以这样做:

 <TextBlock Text="Line1
Line 2"/>

x0A 是转义的十六进制换行符。相当于\n

For completeness: You can also do this:

 <TextBlock Text="Line1
Line 2"/>

x0A is the escaped hexadecimal Line Feed. The equivalent of \n

葬心 2024-12-28 08:31:46

您必须使用

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

Or 如果您愿意:

 <SomeObject xml:space="preserve" />  once upon a time... 
 this line below < / SomeObject>

请注意:如果您都使用 &10 并且转到文本中的下一行,您将有两个空行。

详细信息请参见此处:
http://msdn.microsoft.com/en-us/library/ms788746.aspx

you must use

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

Or if you prefer :

 <SomeObject xml:space="preserve" />  once upon a time... 
 this line below < / SomeObject>

watch out : if you both use &10 AND you go to the next line in your text, you'll have TWO empty lines.

here for details :
http://msdn.microsoft.com/en-us/library/ms788746.aspx

一身仙ぐ女味 2024-12-28 08:31:46

您还可以使用绑定

<TextBlock Text="{Binding MyText}"/>

并像这样设置 MyText:

Public string MyText
{
    get{return string.Format("My Text \n Your Text");}
}

You can also use binding

<TextBlock Text="{Binding MyText}"/>

And set MyText like this:

Public string MyText
{
    get{return string.Format("My Text \n Your Text");}
}
小草泠泠 2024-12-28 08:31:46

尽管这是一个老问题,但我刚刚遇到这个问题并以与给定答案不同的方式解决它。也许对其他人有帮助。

我注意到,尽管我的 XML 文件看起来像:

<tag>
 <subTag>content with newline.\r\nto display</subTag>
</tag>

当它被读入我的 C# 代码时,该字符串有双反斜杠。

\\r\\n

为了解决这个问题,我编写了一个 ValueConverter 来去除多余的反斜杠。

public class XmlStringConverter : IValueConverter
{
    public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        string valueAsString = value as string;
        if (string.IsNullOrEmpty(valueAsString))
        {
            return value;
        }

        valueAsString = valueAsString.Replace("\\r\\n", "\r\n");
        return valueAsString;
    }

    public object ConvertBack(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Even though this is an old question, I've just come across the problem and solved it differently from the given answers. Maybe it could be helpful to others.

I noticed that even though my XML files looked like:

<tag>
 <subTag>content with newline.\r\nto display</subTag>
</tag>

When it was read into my C# code the string had double backslashes.

\\r\\n

To fix this I wrote a ValueConverter to strip the extra backslash.

public class XmlStringConverter : IValueConverter
{
    public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        string valueAsString = value as string;
        if (string.IsNullOrEmpty(valueAsString))
        {
            return value;
        }

        valueAsString = valueAsString.Replace("\\r\\n", "\r\n");
        return valueAsString;
    }

    public object ConvertBack(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
少女情怀诗 2024-12-28 08:31:46

如果其他方法都失败了,你也可以使用

"My text needs a line break here" + System.Environment.NewLine + " This should be a new line"

If all else fails you can also use

"My text needs a line break here" + System.Environment.NewLine + " This should be a new line"
明天过后 2024-12-28 08:31:46
<TextBlock Margin="4" TextWrapping="Wrap" FontFamily="Verdana" FontSize="12">
        <Run TextDecorations="StrikeThrough"> Run cannot contain inline</Run>
        <Span FontSize="16"> Span can contain Run or Span or whatever 
            <LineBreak />
        <Bold FontSize="22" FontFamily="Times New Roman" >Bold can contains 
            <Italic>Italic</Italic></Bold></Span>
</TextBlock>
<TextBlock Margin="4" TextWrapping="Wrap" FontFamily="Verdana" FontSize="12">
        <Run TextDecorations="StrikeThrough"> Run cannot contain inline</Run>
        <Span FontSize="16"> Span can contain Run or Span or whatever 
            <LineBreak />
        <Bold FontSize="22" FontFamily="Times New Roman" >Bold can contains 
            <Italic>Italic</Italic></Bold></Span>
</TextBlock>
楠木可依 2024-12-28 08:31:46

使用 System.Environment.NewLine 是唯一对我有用的解决方案。
当我尝试 \r\n 时,它只是在文本框中重复实际的 \r\n 。

Using System.Environment.NewLine is the only solution that worked for me.
When I tried \r\n, it just repeated the actual \r\n in the text box.

归属感 2024-12-28 08:31:46

只是根据@Ketobomb的建议,你可以按照你的风格使用它吗:

 <Style x:Key="TextBlockTestStyle" TargetType="TextBlock">       
    <Setter Property="Text" Value="line1!
Line2
Line3"/>
 </Setter>

并以这种方式使用它:

 <TextBlock x:Name="TextBlockTest" Style="{StaticResource TextBlockTestStyle}"/>

just from the @Ketobomb suggestion, could you use this in your style:

 <Style x:Key="TextBlockTestStyle" TargetType="TextBlock">       
    <Setter Property="Text" Value="line1!
Line2
Line3"/>
 </Setter>

and use it in this way:

 <TextBlock x:Name="TextBlockTest" Style="{StaticResource TextBlockTestStyle}"/>
雅心素梦 2024-12-28 08:31:46

在 RichTextBox“rtb”中插入“换行符”或“段落符”,如下所示:

var range = new TextRange(rtb.SelectionStart, rtb.Selection.End); 
range.Start.Paragraph.ContentStart.InsertLineBreak();
range.Start.Paragraph.ContentStart.InsertParagraphBreak();

获取 NewLine 项的唯一方法是首先插入带有“\r\n”项的文本,然后应用更多有效的代码在 Selection 和/或 TextRange 对象上。这可确保 \par 项目转换为 \line 项目、根据需要保存,并且在重新打开 *.Rtf 文件时仍然正确。这是我经过努力尝试后发现的。我的三个代码行需要被更多代码(带有循环)包围,以将 TextPointer 项(.Start .End .ContentStart .ContentEnd)设置为行和中断应该去的位置,我已经成功地完成了我的目的。

Insert a "line break" or a "paragraph break" in a RichTextBox "rtb" like this:

var range = new TextRange(rtb.SelectionStart, rtb.Selection.End); 
range.Start.Paragraph.ContentStart.InsertLineBreak();
range.Start.Paragraph.ContentStart.InsertParagraphBreak();

The only way to get the NewLine items is by inserting text with "\r\n" items first, and then applying more code which works on Selection and/or TextRange objects. This makes sure that the \par items are converted to \line items, are saved as desired, and are still correct when reopening the *.Rtf file. That is what I found so far after hard tries. My three code lines need to be surrounded by more code (with loops) to set the TextPointer items (.Start .End .ContentStart .ContentEnd) where the Lines and Breaks should go, which I have done with success for my purposes.

海拔太高太耀眼 2024-12-28 08:31:46
        StringBuilder somestext = new StringBuilder();
        somestext.AppendLine("this is some text on line 1");
        somestext.AppendLine(TB_Tag_Linebreak);
        somestext.AppendLine("this is some more text on line 2"); 
        return somestext.ToString();
        StringBuilder somestext = new StringBuilder();
        somestext.AppendLine("this is some text on line 1");
        somestext.AppendLine(TB_Tag_Linebreak);
        somestext.AppendLine("this is some more text on line 2"); 
        return somestext.ToString();
君勿笑 2024-12-28 08:31:46

定义一个属性,在设置时将 \n 替换为 System.Environment.Newline

private string _data;
public string Data
{
    get => _data; 
    set {
        _data = value.Replace("\\n", System.Environment.NewLine);
        OnPropertyChanged();
    }
}

将文本框绑定到该属性:

<TextBox Text="{Binding Data}" />

读取 xml 数据并将其分配给属性

Data = ...data fetched from xml...

Any \n xml 数据中的数据在 TextBox 中显示为新行。

Define a property which replaces \n with System.Environment.Newline on set:

private string _data;
public string Data
{
    get => _data; 
    set {
        _data = value.Replace("\\n", System.Environment.NewLine);
        OnPropertyChanged();
    }
}

Bind your textbox to the property:

<TextBox Text="{Binding Data}" />

Read the xml data and assign it to the property

Data = ...data fetched from xml...

Any \n in the xml data is displayed as a new line in the TextBox.

べ繥欢鉨o。 2024-12-28 08:31:46

如果您要绑定内容,这非常有效:

<TextBlock>
   <Run Text="{Binding Text1}"/> <LineBreak/>
   <Run Text="{Binding Text2}"/> <LineBreak/>
   <Run Text="{Binding Text3}"/>
</TextBlock>

In case you are binding the content, this works very well:

<TextBlock>
   <Run Text="{Binding Text1}"/> <LineBreak/>
   <Run Text="{Binding Text2}"/> <LineBreak/>
   <Run Text="{Binding Text3}"/>
</TextBlock>
迷途知返 2024-12-28 08:31:46

您必须确保文本块启用了此选项:

AcceptsReturn="True"

You have to ensure that the textblock has this option enabled:

AcceptsReturn="True"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文