Replace RichTextBox text but keep formatting

Can someone highlight this for me, I have a RichTextBox that loads the xaml file into it. I need to replace some parts of the RichTxtBox text with real data, that is, "[our_name]" is replaced by "Billie Brags". My xaml file contains formatting like bold and font size.

When I run my code (shown below), I can change the text OK, but I will lose the formatting.

Any idea how I can do this and save the formatting?

thanks

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); using (fs) { TextRange RTBText = new TextRange(rtb_wording.Document.ContentStart, rtb_wording.Document.ContentEnd); RTBText.Load(fs, DataFormats.Xaml); } TextRange tr = new TextRange(rtb_wording.Document.ContentStart, rtb_wording.Document.ContentEnd); string rtbContent = tr.Text; rtbContent = rtbContent.Replace("<our_name>", "Billie Brags"); System.Windows.MessageBox.Show(rtbContent); FlowDocument myFlowDoc = new FlowDocument(); // Add paragraphs to the FlowDocument myFlowDoc.Blocks.Add(new Paragraph(new Run(rtbContent))); rtb_wording.Document = myFlowDoc; 
+4
source share
2 answers

His work, this is how I did it, in the end, is not too pretty, but it functions. WPF RTB really should have the rtf property as winforms ...

Thanks to Kent for putting me on the right track.

  var textRange = new TextRange(rtb_wording.Document.ContentStart, rtb_wording.Document.ContentEnd); string rtf; using (var memoryStream = new MemoryStream()) { textRange.Save(memoryStream, DataFormats.Rtf); rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray()); } rtf = rtf.Replace("<our_name>", "Bob Cratchet"); MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtf)); rtb_wording.SelectAll(); rtb_wording.Selection.Load(stream, DataFormats.Rtf); 
+5
source

I believe that you need to save the contents of the TextRange in RTF format, and then reload the contents of RTB. I have not tried this, so I'm not sure that it will work (on linux at the moment I can’t check this):

 var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); string rtf; using (var memoryStream = new MemoryStream()) using (var streamReader = new StreamReader(memoryStream)) { textRange.Save(memoryStream, DataFormats.Rtf); rtf = streamReader.ReadToEnd(); } rtf = rtf.Replace("<whatever>", "whatever else"); using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(rtf))) { textRange.Load(memoryStream, DataFormats.Rtf); } 
+1
source

Source: https://habr.com/ru/post/1335664/


All Articles