簡體   English   中英

Wpf 將文本替換為 RichTextBox

[英]Wpf Replace Text into 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 的所有格式

謝謝

嘗試這個 :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM