2011-01-15 28 views
4

誰でも私のためにこれにいくつかの光を投げてもいいですか、私はそれにxamlファイルを読み込んでいるRichTextBoxを持っています。 RichTxtBoxのテキストの特定の部分を実際のデータに置き換える必要があります。つまり、[[our_name] 'は' Billie Brags 'に置き換えられます。私のxamlファイルには太字の&のフォントサイズのような書式が含まれています。RichTextBoxテキストを置き換えても書式を維持する

私のコードを実行すると(下図参照)、テキストはOKに変更できますが、フォーマットが失われます。

どのように私はこれを行うことができ、フォーマットを維持するか考えていますか?

は、私はあなたがRTF形式でTextRangeの内容を保存し、RTBの内容をリロードする必要があります信じて

  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; 

答えて

5

その作業は、これは、あまりにもかわいいけど、それはありません機能。 WPF RTBは本当にwinformsのようなrtfプロパティを持っているはずです...

私は正しい軌道に乗ってくれてありがとうKentに感謝します。

  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); 
+4

また、 'UTF32Encoding.Default.GetString(memoryStream.ToArray());を使用すると便利です。 –

+0

待機UTF32Encodingは、Unicodeテキストにいくつかの問題を与えます。 UTF8Encodingさえ。うーん.. –

1

ありがとうございます。私はそれが(そうテストすることはできません現時点ではLinux上で)動作しますので、わからない、これを試していない:私は最後にそれをやった方法

var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); 
string rtf; 

using (var memoryStream = new MemoryStream()) 
using (var streamReader = new StreamReader(memoryStream)) 
{ 
    textRange.Save(memoryStream, DataFormats.Rtf); 
    rtf = streamReader.ReadToEnd(); 
} 

rtf = rtf.Replace("<whatever>", "whatever else"); 

using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(rtf))) 
{ 
    textRange.Load(memoryStream, DataFormats.Rtf); 
} 
+0

ツールキットのRichTextBoxを使用していますか? WPF 4のものはそのようなプロパティを持っていないので... –

+0

私の悪い - Winforms RTBを考えていた。 –

+0

更新しました。 –

関連する問題