wpf 将新段落附加到 RichTextBox
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28640039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append New Paragraph To RichTextBox
提问by John Steed
I need to programmatically add a new paragraph to a RichTextBox control (just like pressing Enter). Using the code below, it does add a new paragraph but:
我需要以编程方式向 RichTextBox 控件添加一个新段落(就像按 Enter 键一样)。使用下面的代码,它确实添加了一个新段落,但是:
- It deletes all the existing text in the control
- The insertion point remains in the first line and doesn't move to the second newly created line
It only seems to add a new paragraph once, i.e. if I run the code a second time, a third paragraph isn't created
FlowDocument flowDoc= rtbTextContainer.Document; Paragraph pr = new Paragraph(); flowDoc.Blocks.Add(pr); rtbTextContainer.Document = flowDoc;
- 它删除控件中的所有现有文本
- 插入点保留在第一行,不会移动到第二个新创建的行
它似乎只添加了一次新段落,即如果我第二次运行代码,则不会创建第三段
FlowDocument flowDoc= rtbTextContainer.Document; Paragraph pr = new Paragraph(); flowDoc.Blocks.Add(pr); rtbTextContainer.Document = flowDoc;
I was testing a few things - I commented out the second and third lines of code, so I was only reading the Document and immediately set it back to the RichTextBox again, but that also deleted all existing text, so the issue might have something to do with that, but I can't figure it out.
我正在测试一些东西 - 我注释掉了第二行和第三行代码,所以我只是在阅读文档并立即将其重新设置回 RichTextBox,但这也删除了所有现有文本,因此该问题可能有一些问题这样做,但我无法弄清楚。
How can I overcome these issues and programmatically append a new paragraph, and then set its focus.
我如何克服这些问题并以编程方式附加一个新段落,然后设置其焦点。
Thanks
谢谢
回答by dbvega
Part of the view:
部分观点:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<RichTextBox x:Name="RichTextBox1"/>
<Button Grid.Row="1" Content="click-me" Click="Button_Click"/>
</Grid>
And the code behind:
以及背后的代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Run(string.Format("Paragraph Sample {0}", Environment.TickCount)));
RichTextBox1.Document.Blocks.Add(paragraph);
RichTextBox1.Focus();
RichTextBox1.ScrollToEnd();
}
I hope it helps.
我希望它有帮助。

