替换 RichTextBox 文本但保留格式
任何人都可以帮我解释一下这个问题吗?我有一个 RichTextBox,我正在将 xaml 文件加载到其中。我需要用真实数据替换 RichTxtBox 文本的某些部分,即“[our_name]”替换为“Billie Brags”。我的 xaml 文件包含粗体和粗体等格式。字体大小。
当我运行代码(如下所示)时,我可以更改文本,但我会丢失格式。
知道我该如何做到这一点并保持格式吗?
谢谢
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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它的工作原理,这就是我最终做到的,不是太漂亮,但它的功能。 WPF RTB 确实应该像 winforms 一样具有 rtf 属性...
感谢 Kent 让我走上了正确的道路。
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.
我相信您需要以 RTF 格式保存
TextRange
的内容,然后重新加载 RTB 的内容。我还没有尝试过,所以不确定它是否有效(目前在 Linux 上,所以无法测试):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):