开发者

Replace RichTextBox Text but keep formatting

Can anybody cast some light on this for me, I have a RichTextBox which im loading an xaml file into it. I need to Replace certain Parts of the RichTxtBox's text with real data i.e. '[our_name]' is replaced with 'Billie Brags'. My xaml file contains formatting like bold & font size.

When I run my code (shown below) I can change the text OK but im loosing the formatting.

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

Thank you

            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;


Its working, this is how I did it in the end, not too pretty but it functions. WPF RTB really should have rtf property like 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);


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

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜