问题
I have here my piece of code:
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello")))));
string myText = new TextRange(mainWindow.richtextbox2.Document.ContentStart, mainWindow.richtextbox2.Document.ContentEnd).Text;
//replace two or more consecutive spaces with a single space, and
//replace two or more consecutive newlines with a single newline.
var str = Regex.Replace(myText, @"( |\r?\n)\1+", "$1", RegexOptions.Multiline);
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run(str)))));
I know that Hello will be redundant at first start. I want to remove this redundancy at the same time, I also want to remove the spacing in every textline. This is the screenshot that I have taken during my 3 runs.

How can I fix this? Please modify the code.
EDITED: Here is now the screenshot after I change the XAML of richtextbox. How can I make it start at the very first line?

回答1:
Try this in xaml (i made demo):
<RichTextBox HorizontalAlignment="Left" Height="100" Margin="190,83,0,0" VerticalAlignment="Top" Width="100">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
<FlowDocument>
<Paragraph>
<Run Text="RichTextBox"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
And in code:
//this can be added in your invoke method
mainWindow.Dispatcher.Invoke(new Action(() => DoSomething));
private void DoSomething(){
string myText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
var resultString = Regex.Replace(myText, @"( |\r?\n)\1+", "$1");
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(resultString));
richTextBox.SelectAll();
richTextBox.Selection.Load(stream, DataFormats.Text);
}
Resources (WPF)
回答2:
This could be one option.. it removes some of the spacing, not sure if you want more removed.
<RichTextBox Name="richtextbox2" Height="100" BorderBrush="Black" BorderThickness="1">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>
来源:https://stackoverflow.com/questions/22091767/using-regex-and-updating-text-in-richtextbox-wpf-c-sharp