WPF将文本替换为RichTextBox

我在WPF C#中工作,我想将文本替换为RichtextBox 我加载了包含图片的rtf文件,效果很好。

如果我使用这个:

    ReposLettresFusion m_ReposLettresFusion = new ReposLettresFusion();
    textrange range = new textrange(rtb.Document.ContentStart,rtb.Document.ContentEnd); 
    FileStream fStream = new FileStream(@pPath,FileMode.Create);

    range.Text = m_ReposLettresFusion.Fusion(pPkGuidLettre,range.Text);
    range.Save(fStream,DataFormats.Rtf);
    fStream.Close();

    rtb.LoadRtf(pPath);
    m_ReposLettresFusion = null;
    range = null;

它改变了我的文字,但我失去了所有格式的图片和字体。

我如何替换文本并保留Rtf的所有格式

谢谢

wanderer0 回答:WPF将文本替换为RichTextBox

尝试一下:

public void Fusion(ref Xceed.Wpf.Toolkit.RichTextBox pRichTextControl)
        {

            foreach (KeyValuePair<string,string> entry in LettreFusion)
            {
                string keyword = entry.Key;
                string newString = entry.Value;

                TextRange text = new TextRange(pRichTextControl.Document.ContentStart,pRichTextControl.Document.ContentEnd);
                TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);
                while (current != null)
                {
                    string textInRun = current.GetTextInRun(LogicalDirection.Forward);
                    if (!string.IsNullOrWhiteSpace(textInRun))
                    {
                        int index = textInRun.IndexOf(keyword);
                        if (index != -1)
                        {
                            TextPointer selectionStart = current.GetPositionAtOffset(index,LogicalDirection.Forward);
                            TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length,LogicalDirection.Forward);
                            TextRange selection = new TextRange(selectionStart,selectionEnd);
                            selection.Text = newString;
                            pRichTextControl.Selection.Select(selection.Start,selection.End);
                            pRichTextControl.Focus();
                        }
                    }
                    current = current.GetNextContextPosition(LogicalDirection.Forward);
                }
            }
        }
本文链接:https://www.f2er.com/2953000.html

大家都在问