リッチテキストボックスにテキストがあります。このテキストには、例:[@ TagName!]というタグが含まれています。私は書式設定(フォント、色、画像など)を失うことなく、これらのタグをデータベースのデータで置き換えたいと考えています。私はメソッドを作成しました:XamlPackageのテキストを置き換えます
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();
}
これはかなり良いですが、コンテンツからイメージを削除します。私はXamlの代わりにXamlPackageを使うべきだと知っていますが、それをプレーンテキストとして取得することはできません。これには他の解決策がありますか?
お返事ありがとうございます。 ;)
[EDIT:13-02-2012 2時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);
}
は、多分それはベストではないのですが、それは正しく動作しています。
解決済みです。しかし、私はもうアクセスできない会社のサーバー上にあるので、私は解決策を投稿できません。
私はあなたがXMLではなくXMLPackageを意味すると思います。あなたがイメージを失うところでは、dt.Rows [0] [colname]のcolnameにマッチしますか? – Paparazzi
No. dt.Rows [0] [colname]はデータベースから列名のみを返します。画像はRichTextBoxでユーザーによって追加されます。 – arche89
複数のcolnameエントリがあるため、どこかにループが必要なので、一致の代わりにregex.replaceを使用したとしても、列全体をループする必要があり、データのために無駄な置換を実行する可能性があります実行する必要はありません。それは私の意見ではおそらく最善の答えです。一致を取得し、必要に応じてデータを置き換えます。 – Nevyn