Question

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.

enter image description here

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?

enter image description here

Was it helpful?

Solution

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)

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top