WPF中的RichTextBox

时间:2023-11-21 16:32:50

原文链接:http://blog.csdn.net/wuzhengqing1/article/details/7010902

取出richTextBox里面的内容

第一种方法:将richTextBox的内容以字符串的形式取出

string str = System.Windows.Markup.XamlWriter.Save(richTextBox.Document);

第二种方法:将richTextBox的类容以二进制数据的方法取出

     FlowDocument     doc    = richTextBox.Document;
System.IO.Stream stream = new System.IO.MemoryStream();
System.Windows.Markup.XamlWriter.Save(doc, stream);
byte[] data = new byte[stream.Length];
stream.Position = ;
stream.Read(data, , data.Length);
stream.Close();

赋值给richTextBox

第一种方法:将字符串转换为数据流赋值给richTextBox中

  System.IO.StringReader sr = new System.IO.StringReader(str);
System.Xml.XmlReader xr = System.Xml.XmlReader.Create(sr);
richTextBox1.Document = (FlowDocument)System.Windows.Markup.XamlReader.Load(xr);

第二种方法:将二进制数据赋值给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 para = new Paragraph();//------Paragraph 类似于 html 的 P 标签
Run run = new Run(myString);//----Run 是一个 Inline 的标签
para.Inlines.Add(run);
doc.Blocks.Add(para);
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(, System.IO.SeekOrigin.Begin);
System.IO.StreamReader sr = new System.IO.StreamReader(ms);
rtf = sr.ReadToEnd();
}

RichTextBox的操作:

       using System.Windows.Input;
using System.Windows.Documents;

//---复制,剪切,粘贴,撤销,重做
ToolBarCopy.Command = ApplicationCommands.Copy;
ToolBarCut.Command = ApplicationCommands.Cut;
ToolBarPaste.Command = ApplicationCommands.Paste;
ToolBarUndo.Command = ApplicationCommands.Undo;
ToolBarRedo.Command = ApplicationCommands.Redo;
//---文字居中/右/左
ToolBarContentCenter.Command = EditingCommands.AlignCenter;
ToolBarContentRight.Command = EditingCommands.AlignRight;
ToolBarContentLeft.Command = EditingCommands.AlignLeft;
//---有序/无序排列
ToolBarNumbering.Command = EditingCommands.ToggleNumbering;
ToolBarBullets.Command = EditingCommands.ToggleBullets;//---字体变大
int fontSize = Convert.ToInt32(richTextBox.Selection.GetPropertyValue(
TextElement.FontSizeProperty));
fontSize++;
richTextBox.Selection.ApplyPropertyValue(TextElement.FontSizeProperty,
fontSize.ToString());