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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.