如何在不丢失格式的情况下以编程方式替换 WFP RichTextBox 的某些内容? [英] How to programmatically replace some content of WFP RichTextBox without loosing the formatting?
问题描述
问题:我们如何以编程方式替换 WPF RichTextBox
中的某些文本而不丢失其格式?在下面的代码中,我显然没有做正确的事情.我的在线搜索提供了一些相关建议,但他们似乎正在使用 Winform,其中 RichTextBox 具有 rtf 属性 - 例如
用 rstu 替换 abcd 后 RichTextBox 的屏幕截图:
我们可以看到格式丢失了.下面显示的列表并不是真正的格式化编号列表,它可能只是未格式化的文本(例如 1.Item 1
等)
它正在丢失格式,因为您将 RTF 存储到字符串中,而该字符串不保留 RTF 格式.
您可以将其保存如下,
TextRange textRange = new TextRange(rtbTest.Document.ContentStart, rtbTest.Document.ContentEnd);字符串 rtf;使用 (var memoryStream = new MemoryStream()){textRange.Save(memoryStream, DataFormats.Rtf);rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray());}rtf = rtf.Replace("abcd", "rstu");MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtf));rtbTest.SelectAll();rtbTest.Selection.Load(stream, DataFormats.Rtf);
Question: How can we programmatically replace some text in a WPF RichTextBox
without loosing its formatting? In the following code I am clearly not doing something right. My online search gives some relevant suggestions but they seem to be using Winform where RichTextBox has rtf property - such as this one.
Following code correctly replaces text abcd
with rstu
inside a WPF RichTexBox but it looses the formatting of the RichTextBox as shown in the two images below:
//rtbTest is the name of the RichTextBox
TextRange textRange = new TextRange(rtbTest.Document.ContentStart, rtbTest.Document.ContentEnd);
string oldText = textRange.Text;
string newText = oldText.Replace("abcd", "rstu");
textRange.Text = newText;
Screenshot of RichTextBox BEFORE replacing abcd with rstu:
Screenshot of RichTextBox AFTER replacing abcd with rstu:
As we can see the formatting is lost. The list shown below is not really a formatted numbered list, it probably is just unformatted text (like 1. Item 1
etc.)
It is losing the formatting because you are storing the RTF into a string and the string doesn't keep RTF formatting.
You can preserve it as following,
TextRange textRange = new TextRange(rtbTest.Document.ContentStart, rtbTest.Document.ContentEnd);
string rtf;
using (var memoryStream = new MemoryStream())
{
textRange.Save(memoryStream, DataFormats.Rtf);
rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray());
}
rtf = rtf.Replace("abcd", "rstu");
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtf));
rtbTest.SelectAll();
rtbTest.Selection.Load(stream, DataFormats.Rtf);
这篇关于如何在不丢失格式的情况下以编程方式替换 WFP RichTextBox 的某些内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!