以下內容轉自 http://blog.csdn.net/yulongguiziyao/article/details/25330551。
1. 取得已被選中的內容:
(1)使用 RichTextBox.Document.Selection屬性
(2)訪問RichTextBox.Document.Blocks屬性的“blocks”中的Text
2. 在XAML中增加內容給RichTextBox:
<RichTextBox IsSpellCheckEnabled="True">
<FlowDocument>
<Paragraph>
<!-- 這里加上你的內容 -->
This is a richTextBox. I can <Bold>Bold</Bold>, <Italic>Italicize</Italic>, <Hyperlink>Hyperlink stuff</Hyperlink> right in my document.
</Paragraph>
</FlowDocument>
</RichTextBox>
3. 縮短段間距,類似<BR>,而不是<P>
方法是使用Style定義段間距:
<RichTextBox>
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
<FlowDocument>
<Paragraph>
This is my first paragraph... see how there is...
</Paragraph>
<Paragraph>
a no space anymore between it and the second paragraph?
</Paragraph>
</FlowDocument>
</RichTextBox>
4. 從文件中讀出純文本文件后放進RichTextBox或直接將文本放進RichTextBox中:
private void LoadTextFile(RichTextBox richTextBox, string filename)
{
richTextBox.Document.Blocks.Clear();
using (StreamReader streamReader = File.OpenText(filename)) {
Paragraph paragraph = new Paragraph();
paragraph.Text = streamReader.ReadToEnd();
richTextBox.Document.Blocks.Add(paragraph);
}
}
5.如何在RichTextBox中添加文本
RichTextBox 是WPF中的一個控件,它存儲的內容由其 Document 屬性來呈現。Document 是一個 FlowDocument 類型。
FlowDocument 是放置塊內容(Blocks)和Inlines的容器 。
塊級元素(Block)包括:Paragraph,List,Table,Section
Inline元素包括:Run,Span,Bold、Italic、Underline,Hyperlink,LineBreak,InlineUIContainer,Floater、Figure
richtextbox添加文本代碼:
string myText="hello!";
RichTextBox MyRichTextBox=new RichTextBox ();
FlowDocument doc = new FlowDocument();
Paragraph p = new Paragraph();
Run r = new Run(myText);
p.Inlines.Add(r);//Run級元素添加到Paragraph元素的Inline
doc.Blocks.Add(p);//Paragraph級元素添加到流文檔的塊級元素
MyRichTextBox.Document = doc;
}
6. 取得指定RichTextBox的內容:
private string GetText(RichTextBox richTextBox)
{
TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
return textRange.Text;
}
7. 將RTF (rich text format)放到RichTextBox中:
private static void LoadRTF(string rtf, RichTextBox richTextBox)
{
if (string.IsNullOrEmpty(rtf)) {
throw new ArgumentNullException();
}
TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
using (MemoryStream rtfMemoryStream = new MemoryStream()) {
using (StreamWriter rtfStreamWriter = new StreamWriter(rtfMemoryStream)) {
rtfStreamWriter.Write(rtf);
rtfStreamWriter.Flush();
rtfMemoryStream.Seek(0, SeekOrigin.Begin);
//Load the MemoryStream into TextRange ranging from start to end of RichTextBox.
textRange.Load(rtfMemoryStream, DataFormats.Rtf);
}
}
}
8. 將文件中的內容加載為RichTextBox的內容
private static void LoadFile(string filename, RichTextBox richTextBox)
{
if (string.IsNullOrEmpty(filename)) {
throw new ArgumentNullException();
}
if (!File.Exists(filename)) {
throw new FileNotFoundException();
}
using (FileStream stream = File.OpenRead(filename)) {
TextRange documentTextRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
string dataFormat = DataFormats.Text;
string ext = System.IO.Path.GetExtension(filename);
if (String.Compare(ext, ".xaml",true) == 0) {
dataFormat = DataFormats.Xaml;
}
else if (String.Compare(ext, ".rtf", true) == 0) {
dataFormat = DataFormats.Rtf;
}
documentTextRange.Load(stream, dataFormat);
}
}
9. 將RichTextBox的內容保存為文件:
private static void SaveFile(string filename, RichTextBox richTextBox)
{
if (string.IsNullOrEmpty(filename)) {
throw new ArgumentNullException();
}
using (FileStream stream = File.OpenWrite(filename)) {
TextRange documentTextRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
string dataFormat = DataFormats.Text;
string ext = System.IO.Path.GetExtension(filename);
if (String.Compare(ext, ".xaml", true) == 0) {
dataFormat = DataFormats.Xaml;
}
else if (String.Compare(ext, ".rtf", true) == 0) {
dataFormat = DataFormats.Rtf;
}
documentTextRange.Save(stream, dataFormat);
}
}
10. 做個簡單的編輯器:
<!-- Window1.xaml -->
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_Open File" Click="OnOpenFile"/>
<MenuItem Header="_Save" Click="OnSaveFile"/>
<Separator/>
<MenuItem Header="E_xit" Click="OnExit"/>
</MenuItem>
</Menu>
<RichTextBox Name="richTextBox1"></RichTextBox>
</DockPanel>
// Window1.xaml.cs
private void OnExit(object sender, EventArgs e) {
this.Close();
}
private void OnOpenFile(object sender, EventArgs e) {
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.Filter = "Text Files (*.txt; *.xaml; *.rtf)|*.txt;*.xaml;*.rtf";
ofd.Multiselect = false;
if (ofd.ShowDialog() == true) {
LoadFile(ofd.SafeFileName, richTextBox1);
}
}
private void OnSaveFile(object sender, EventArgs e) {
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.Filter = "Text Files (*.txt; *.xaml; *.rtf)|*.txt;*.xaml;*.rtf";
if (sfd.ShowDialog() == true) {
SaveFile(sfd.SafeFileName, richTextBox1);
}
}
取出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());