WPF中的richtextbox與winform中的richtextbox的使用不同,看看下面的基本操作:
一、取出richTextBox裡面的內容
(1)將richTextBox的內容以字串的形式取出
string xw = System.Windows.Markup.XamlWriter.Save(richTextBox.Document);
(2)將richTextBox的類容以位元據的方法取出
FlowDocument document = richTextBox.Document; System.IO.Stream s = new System.IO.MemoryStream(); System.Windows.Markup.XamlWriter.Save(document, s); byte[] data = new byte[s.Length]; s.Position = 0; s.Read(data, 0, data.Length); s.Close();
二、richTextBox賦值
(1)將字串轉換為資料流賦值給richTextBox中
System.IO.StringReader sr = new System.IO.StringReader(xw); System.Xml.XmlReader xr = System.Xml.XmlReader.Create(sr); richTextBox1.Document = (FlowDocument)System.Windows.Markup.XamlReader.Load(xr);
(2)將位元據賦值給richTextBox
System.IO.Stream ss = new System.IO.MemoryStream(data); FlowDocument doc = System.Windows.Markup.XamlReader.Load(ss) as FlowDocument; ss.Close(); richTextBox1.Document = doc;
三、清空RichTextBox的方法
System.Windows.Documents.FlowDocument doc = RichTextBox.Document;doc.Blocks.Clear();
四、如何將一個String類型的字串賦值給richTextBox
myRTB.Document = new FlowDocument(new Paragraph(new Run(myString))); FlowDocument doc = new FlowDocument(); Paragraph p = new Paragraph(); // Paragraph 類似於 html 的 P 標籤 Run r = new Run(myString); // Run 是一個 Inline 的標籤 p.Inlines.Add(r); doc.Blocks.Add(p); myRTB.Document = doc;
五、將richTextBox中的內容以rtf的格式完全取出
string rtf = string.Empty; TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { textRange.Save(ms, System.Windows.DataFormats.Rtf); ms.Seek(0, System.IO.SeekOrigin.Begin); System.IO.StreamReader sr = new System.IO.StreamReader(ms); rtf = sr.ReadToEnd(); }
六、其他動作
複製: ToolBarCopy.Command = System.Windows.Input.ApplicationCommands.Copy; 剪下: toolBarCut.Command = System.Windows.Input.ApplicationCommands.Cut; 粘貼: ToolBarPaste.Command = System.Windows.Input.ApplicationCommands.Paste; 撤銷: ToolBarUndo.Command = System.Windows.Input.ApplicationCommands.Undo; 複原: ToolBarRedo.Command = System.Windows.Input.ApplicationCommands.Redo; 文字置中: toolBarContentCenter.Command = System.Windows.Documents.EditingCommands.AlignCenter; 文字居右: toolBarContentRight.Command = System.Windows.Documents.EditingCommands.AlignRight; 文字居左: toolBarContentLeft.Command = System.Windows.Documents.EditingCommands.AlignLeft; 有序排列: ToolBarNumbering.Command = System.Windows.Documents.EditingCommands.ToggleNumbering; 無序排列: ToolBarBullets.Command = System.Windows.Documents.EditingCommands.ToggleBullets; 字型變大: int fontSize = Convert.ToInt32(richTextBox.Selection.GetPropertyValue(TextElement.FontSizeProperty)); fontSize++; richTextBox.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, fontSize.ToString());