سؤال

I need to get exactly all text from a WPF RichTextBox.

Everyone (How to get a WPF rich textbox into a string, RichTextBox (WPF) does not have string property "Text", http://msdn.microsoft.com/en-us/library/ms754041(v=vs.110).aspx and many more) agrees a code like this one:

public static string GetText(RichTextBox rtb)
{
    TextRange textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
    string text = textRange.Text;
    return text;
}

but it add a trailling "\r\n". In a very simple case:

<RichTextBox x:Name="mRichTextBox">
  <FlowDocument>
    <Section>
      <Paragraph>
        <Run Text="The dog is brown. The cat is black."/>
      </Paragraph>
    </Section>
  </FlowDocument>
</RichTextBox>

I get:

"The dog is brown. The cat is black.\r\n"

It can be seen as a minor issue but really I need exact text.

  • Do you know why?
  • Is it safe to simply ignore one trailing "\r\n"?
  • Is my code correct?
  • Is there any other gotcha (I mean differences between real text and what I get from my GetText)?

Thanks.

هل كانت مفيدة؟

المحلول

If you don't need the multiline you can disable it and shouldn't have this problem.

You could also remove them like this:

  string text = textRange.Text.Replace(Environment.NewLine, "");

Also if you only want to remove the last ocurrence you can use a function like this:

public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
    int Place = Source.LastIndexOf(Find);
    string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
    return result;
}

And use it like this.

 string text = ReplaceLastOccurrence(textRange.Text,Environment.NewLine,"");

Every time you have a you will get a New Line at the end, so make sure you handle it acordingly.

نصائح أخرى

But you are getting the actual text.
You don't think a parargraph should end with a new line?

Try this and copy paste from the screen to notepad

<RichTextBox x:Name="mRichTextBox">
    <FlowDocument>
        <Section>
            <Paragraph/>
            <Paragraph/>
            <Paragraph>
                <Run Text="The dog is brown. The cat is black."/>
            </Paragraph>
        </Section>
    </FlowDocument>
</RichTextBox>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top