I work in WPF C#, i want to replace text into RichtextBox i load my rtf File who contain picture it's work fine.
If i use this :
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;
It's change my text but i loose my picture and fonts all my formatting.
How i can replace text and keep all formatting of the Rtf
Thank you
Try this :
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);
}
}
}