【发布时间】:2012-02-10 13:19:48
【问题描述】:
我在 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();
}
这很好,但它会从内容中删除图像。我知道我应该使用 XamlPackage 而不是 Xaml,但是我无法将它作为纯文本获取。有没有其他解决方案?
感谢您的回答。 ;)
[编辑:13-02-2012 02:14(am)]
我的工作解决方案:
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);
}
也许它不是最好的,但它工作正常。
解决了。但我无法发布解决方案,因为它位于我无法再访问的公司服务器上。
【问题讨论】:
-
我认为您的意思是 XMLPackage 而不是 XML。丢失图像的位置是否在 dt.Rows[0][colname] 的 colname 上找到匹配项?
-
没有。 dt.Rows[0][colname] 只给我数据库中的列名。图片由用户添加到 RichTextBox 中。
-
由于有多个 colname 条目,您需要在某处进行循环,因此即使您确实使用了 regex.replace 而不是 match,您仍然需要遍历列,并且可能会结束由于不需要运行的数据,运行无用的替换。在我看来,这可能是最好的答案。获取匹配项,然后根据需要替换数据。
标签: c# wpf string flowdocument