Tin*_*ren 4 wpf replace 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;
Run Code Online (Sandbox Code Playgroud)
它的工作原理,这就是我最终做到的,不是太漂亮但它的功能.WPF RTB真的应该有像winforms这样的rtf属性......
感谢肯特让我走上正轨.
var textRange = new TextRange(rtb_wording.Document.ContentStart, rtb_wording.Document.ContentEnd);
string rtf;
using (var memoryStream = new MemoryStream())
{
textRange.Save(memoryStream, DataFormats.Rtf);
rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray());
}
rtf = rtf.Replace("<our_name>", "Bob Cratchet");
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtf));
rtb_wording.SelectAll();
rtb_wording.Selection.Load(stream, DataFormats.Rtf);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6473 次 |
| 最近记录: |