2009-09-02 126 views
26

我有這樣的RTF文本:設置RTF文本WPF RichTextBox控件

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial;}} 
{\colortbl ;\red0\green0\blue0;\red255\green0\blue0;} 
\viewkind4\uc1\pard\qc\cf1\fs16 test \b bold \cf2\b0\i italic\cf0\i0\fs17 
\par } 

如何設置這個文本WPF RichTextBox


解決方案:

public void SetRTFText(string text) 
{ 
    MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(text)); 
    this.mainRTB.Selection.Load(stream, DataFormats.Rtf); 
} 

Thanks for help from Henk Holterman.

+0

僅有1句話,你確定你想ASCII編碼?它可能只是UTF8或默認通常更有意義。 – 2009-09-02 16:35:17

+0

是的,如果我有,ASCII編碼是我需要使用的。謝謝你的提示:) – 2009-09-02 17:12:38

+0

實際上,你不**使用這個代碼使用ASCII編碼......'Default'實際上是指'Encoding.Default',所以它是系統的默認ANSI代碼頁。注意通過派生類訪問靜態成員,這往往是誤導。 – 2013-12-31 10:42:58

回答

33

你真的要開始一個字符串?

一種方法來加載RTF是這樣的:

rtfBox.Selection.Load(myStream, DataFormats.Rtf); 

你或許應該致電前全選()如果要替換現有文本。因此,最糟糕的情況是,您必須將字符串寫入MemoryStream,然後將該數據流送入Load()方法。不要忘記在兩者之間的位置= 0。

但我在等待看到有人想出更優雅的東西。

+0

rtfBox.Selection.Load是我所需要的。謝謝:) – 2009-09-02 15:27:23

+8

代替使用'Selection'屬性並擔心調用SelectAll,您可能可以使用'新的TextRange(rtfBox.Document.ContentStart,rtfBox.Document.ContentEnd)',然後在TextRange上調用Load(Selection is本身是一個TextRange)。 – devios1 2010-06-01 01:51:26

+0

with devios's snippet,this works:'TextRange textRange = new TextRange(rtfBox.Document.ContentStart,rtfBox.Document.ContentEnd); MemoryStream ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(rtfText)); textRange.Load(ms,DataFormats.Rtf);' – 2016-02-02 16:05:20

-2

只需使用RichTextBox.Rtf:

string rtf = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial;}} {\colortbl ;\red0\green0\blue0;\red255\green0\blue0;} \viewkind4\uc1\pard\qc\cf1\fs16 test \b bold \cf2\b0\i italic\cf0\i0\fs17 \par } "; 
richTextBox1.Rtf = rtf; 
+1

這適用於WinForms RichTextBox – 2009-09-02 12:11:16

+0

哦,我的不好。我想你在哪裏使用WPF。 – 2009-09-02 12:22:11

+0

你回答幫助我,所以投票。 – 2011-09-13 08:48:26

4

創建一個擴展方法

public static void SetRtf(this RichTextBox rtb, string document) 
    { 
     var documentBytes = Encoding.UTF8.GetBytes(document); 
     using (var reader = new MemoryStream(documentBytes)) 
     { 
      reader.Position = 0; 
      rtb.SelectAll(); 
      rtb.Selection.Load(reader, DataFormats.Rtf); 
     } 
    } 

然後,你可以做的WinForm式的風格

richTextBox1.SetRtf(rtf);

+0

您不能使用擴展方法作爲屬性。 – 2012-12-09 19:23:03