2011-01-15 3 views
4

누구든지 나를 위해이 부분에 조명을 적용 할 수 있습니까, 저는 RichTextBox에 xaml 파일을로드합니다. RichTxtBox 텍스트의 특정 부분을 실제 데이터로 바꾸어야합니다. 즉, '[our_name]'은 'Billie Brags'로 바뀝니다. 내 xaml 파일에 굵게 글꼴 & 같은 서식이 포함되어 있습니다.RichTextBox 텍스트를 바꾸지 만 서식을 유지하십시오.

코드를 실행할 때 (아래 참조) 텍스트를 바꿀 수 있지만 형식이 잘못되었습니다.

어떻게하면이 작업을 수행하고 서식을 유지할 수 있습니까?

내가 당신이 RTB의 내용을 RTF 형식으로 TextRange의 내용을 저장 한 다음 다시로드해야합니다 믿고 당신에게

  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 속성이 있어야합니다 ...

옳은 트랙에 날 놔 줘서 고마워.

  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은 유니 코드 텍스트에 몇 가지 문제점을 제공합니다. 심지어 UTF8Encoding. 흠 .. –

1

감사드립니다. 나는 그것이 (그래서 테스트 할 수 없습니다 순간에 리눅스에) 작동 확신하지이 시도하지 않은 : 나는 결국 그것을 어떻게

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

업데이트했습니다. –

관련 문제