wpf 操作richtextbox

取出richTextBox里面的内容
第一种方法:将richTextBox的内容以字符串的形式取出
string xw = System.Windows.Markup.XamlWriter.Save(richTextBox.Document);
第二种方法:将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

 

第一种方法:将字符串转换为数据流赋值给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);
第二种方法:将二进制数据赋值给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();
}
 

 

 

 

操作RichTextBox
复制 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());

转自:http://blog.163.com/kunkun0921@126/blog/static/1692043322011121104652932/

发表评论