WPF 多行 TextBlock 换行问题

发布于 2024-10-11 10:19:51 字数 811 浏览 1 评论 0原文

我有以下代码

txtBlock1.Inlines.Add("This is first paragraph \n This is second paragraph");

,然后 TextBlock 将显示:

This is first paragraph
This is second paragraph

但是,如果我有以下代码(我认为这是等效的);

txtBlock1.Inlines.Add("This is first paragraph");
txtBlock1.Inlines.Add("\n");
txtBlock1.Inlines.Add("This is second paragraph");

TextBlock 显示:

This is first paragraph // but second paragraph missing

如果我将换行符分开,则换行符后的其余文本不会显示。为什么?

我必须使用 run:

Run run1 = new Run();
run1.Text = "First Paragraph";
run1.Text += "\n";
run1.Text += "Second Paragraph";
txtBlock1.Inlines.Add(run1); 

然后它会正确产生结果。为什么我无法将内联文本添加到 Textblock 并要求我使用 Run

I have the following code

txtBlock1.Inlines.Add("This is first paragraph \n This is second paragraph");

then TextBlock would display:

This is first paragraph
This is second paragraph

But, if I have the following (which I though is equivalent);

txtBlock1.Inlines.Add("This is first paragraph");
txtBlock1.Inlines.Add("\n");
txtBlock1.Inlines.Add("This is second paragraph");

TextBlock display:

This is first paragraph // but second paragraph missing

If I separate out the linebreak then the rest of text after the linebreak doesn't show. Why?

I have to use run:

Run run1 = new Run();
run1.Text = "First Paragraph";
run1.Text += "\n";
run1.Text += "Second Paragraph";
txtBlock1.Inlines.Add(run1); 

Then it produce the result correctly. Why I cannot add inline text to Textblock and require me to use Run?

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

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

发布评论

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

评论(1

避讳 2024-10-18 10:19:51

请参阅此答案:什么在 WPF 文本块中获取段落的最佳方法? (换行符?)

您需要:

txtBlock1.Inlines.Add("This is first paragraph");
txtBlock1.Inlines.Add(new LineBreak());
txtBlock1.Inlines.Add("This is second paragraph");

See this answer: What the best way to get paragraphs in a WPF textblock? (newline chars?)

You need:

txtBlock1.Inlines.Add("This is first paragraph");
txtBlock1.Inlines.Add(new LineBreak());
txtBlock1.Inlines.Add("This is second paragraph");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文