Art*_*luk 41 c# string wpf flowdocument
我在RichTextBox中有一些文本.此文本包含标签,例如:[@TagName!].我想用数据库中的一些数据替换这些标签而不会丢失格式(字体,颜色,图像等).我创建了一个方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
它非常好,但它从内容中删除图像.我知道我应该使用XamlPackage而不是Xaml但是我不能把它作为纯文本.还有其他解决方案吗?
谢谢你的回答.;)
[编辑:2012年2月13日02:14(上午)]
我的工作方案:
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);
}
Run Code Online (Sandbox Code Playgroud)
也许它不是最好的,但它正常工作.
它解决了.但我不能发布解决方案,因为它是在公司服务器上,我无法访问.
您可以使用 Razor 引擎在模板主题中执行您想要的任何操作。您可以从 nuget ( http://www.nuget.org/packages/RazorEngine )下载,无需任何设置配置,您就可以使用 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>
Run Code Online (Sandbox Code Playgroud)
注意:@Model.Title 和 @Model.Icon 来自 Razor
实际上,我使用 RazorEngine 来完成所有模板任务:电子邮件、动态报告生成 (rdlc) 等......
归档时间: |
|
查看次数: |
2067 次 |
最近记录: |