replaceXamlPackage中的文本

我在RichTextBox中有一些文本。 此文本包含标签,例如:[@标签名称!]。 我想用数据库中的一些数据replace这些标签,而不会丢失格式(字体,颜色,图像等)。 我创build了一个方法:

void ReplaceTagsWithData(FlowDocument doc) { FileStream fs = new FileStream("tmp.xml", FileMode.Create); TextRange trTextRange = new TextRange(doc.ContentStart, doc.ContentEnd); trTextRange.Save(fs, DataFormats.Xaml); fs.Dispose(); fs.Close(); StreamReader sr = new StreamReader("tmp.xml"); string rtbContent = sr.ReadToEnd(); MatchCollection mColl = Regex.Matches(rtbContent, string.Format(@"\{0}+[a-zA-Z]+{1}", prefix, postfix)); foreach (Match m in mColl) { string colname = m.Value.Substring(prefix.Length, (int)(m.Value.Length - (prefix.Length + postfix.Length))); rtbContent = rtbContent.Replace(m.Value.ToString(), dt.Rows[0][colname].ToString()); } rtbEdit.Document = new FlowDocument( (Section)XamlReader.Load( XmlReader.Create(new StringReader(rtbContent)))); sr.Dispose(); sr.Close(); } 

这是相当不错的,但它从内容中删除图像。 我知道我应该使用XamlPackage而不是Xaml,但是我不能把它作为纯文本。 有没有其他解决scheme呢?

感谢您的回答。 ;)

[编辑:13-02-2012 02:14(上午)]

我的工作解决scheme

  void ReplaceTagsWithData(RichTextBox rtb) { FlowDocument doc = rtb.Document; FileStream fs = new FileStream("tmp", FileMode.Create); TextRange trTextRange = new TextRange(doc.ContentStart, doc.ContentEnd); trTextRange.Save(fs, DataFormats.Rtf); fs.Dispose(); fs.Close(); StreamReader sr = new StreamReader("tmp"); string rtbContent = sr.ReadToEnd(); sr.Dispose(); sr.Close(); MatchCollection mColl = Regex.Matches(rtbContent, string.Format(@"\{0}+[a-zA-Z]+{1}", prefix, postfix)); foreach (Match m in mColl) { string colname = m.Value.Substring(prefix.Length, (int)(m.Value.Length - (prefix.Length + postfix.Length))); rtbContent = rtbContent.Replace(m.Value.ToString(), dt.Rows[0][colname].ToString()); } MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtbContent)); rtb.SelectAll(); rtb.Selection.Load(stream, DataFormats.Rtf); } 

也许这不是最好的,但它工作正常。

它被解决了。 但我无法发布解决scheme,因为它在公司服务器上,我不能访问了。

您可以使用Razor引擎在模板主题中执行任何您想要的操作。 你可以从nuget下载( http://www.nuget.org/packages/RazorEngine ),没有任何设置configuration,你可以使用Razor语法来做到这一点。 例如你的模板可以是这样的:

 <Window x:Class="<class>" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="@Model.Title" Icon="@Model.Icon"> <Grid> </Grid> </Window> 

注意:来自Razor的@ Model.Title和@ Model.Icon

其实我使用RazorEngine所有我的模板任务:电子邮件,飞行报告(rdlc)等等…

您可以使用Aspose.dll。 它具有完整的论坛/示例和文档使用aspose.dllreplace基于正则expression式的文本

你正在使用的正则expression式是贪婪的,所以会匹配从一个标记开始到下一个标记结束的所有内容。 将其更改为@"\{0}[a-zA-Z]+?{1}"以获得更好的匹配。

另外,使用Regex.Replace的重载需要一个lambda将是更干净的代码。

尝试使用Regex.Replace方法。 您可以在MSDN中find对该方法的引用http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx