以下内容转自 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());

WPF RichTextBox 控件常用方法和属性的更多相关文章

  1. WPF系列 —— 控件添加依赖属性(转)

    WPF系列 —— 控件添加依赖属性 依赖属性的概念,用途 ,如何新建与使用.本文用做一个自定义TimePicker控件来演示WPF的依赖属性的简单应用. 先上TimePicker的一个效果图. 概念 ...

  2. [WPF]Slider控件常用方法

    WPF的Slider控件继承自RangeBase类型,同继承自RangeBase的控件还有ProgressBar和ScrollBar,这类控件都是在一定数值范围内表示一个值的用途. 首先注意而Rang ...

  3. WPF系列 —— 控件添加依赖属性

    依赖属性的概念,用途 ,如何新建与使用.本文用做一个自定义TimePicker控件来演示WPF的依赖属性的简单应用. 先上TimePicker的一个效果图. 概念 和 用途:依赖属性是对传统.net ...

  4. WPF Image控件的Source属性是一个ImageSource对象

    1.固定的图片路径是可以的,如下: <Image Source="../test.png" /> 2.绑定的Path是一个String类型的图片路径,而实际情况它需要的 ...

  5. WPF 用户控件的自定义依赖属性在 MVVM 模式下的使用备忘

    依赖属性相当于扩充了 WPF 标签的原有属性列表,并可以使用 WPF 的绑定功能,可谓是十分方便的:用户控件则相当于代码重用的一种方式:以上几点分开来还是比较好理解的,不过要用到MVVM 模式中,还是 ...

  6. 设置RichTextBox控件的文本的对齐方式

    实现效果: 知识运用: RichTextBox控件的SelectionAlignment属性 //获取或设置在当前选择或插入点的对齐方式 public HorizontalAlignment Sele ...

  7. 在RichTextBox控件中替换文本文字

    实现效果: 知识运用: RichTextBox控件的SelectedText属性 实现代码: private void button1_Click(object sender, EventArgs e ...

  8. WPF布局控件与子控件的HorizontalAlignment/VerticalAlignment属性之间的关系

    WPF布局控件与子控件的HorizontalAlignment/VerticalAlignment属性之间的关系: 1.Canvas/WrapPanel控件: 其子控件的HorizontalAlign ...

  9. 【转】WPF中PasswordBox控件的Password属性的数据绑定

    英文原文:http://www.wpftutorial.net/PasswordBox.html 中文原文:http://blog.csdn.net/oyi319/article/details/65 ...

随机推荐

  1. 性能测试之LoardRunner 测试场景监控关注的几点

    1.系统业务处理能力,即通常我们在进行性能测试的时候,在特定的硬件和软件环境下考察的业务处理能力,即“事物”,需要关注当前.平时.峰值以及长远未来业务发展情况,考虑不同业务的处理数量,从而设定相应的业 ...

  2. 什么是CC攻击,如何防止网站被CC攻击的方法总汇

    CC攻击(Challenge Collapsar)是DDOS(分布式拒绝服务)的一种,也是一种常见的网站攻击方法,攻击者通过代理服务器或者肉鸡向向受害主机不停地发大量数据包,造成对方服务器资源耗尽,一 ...

  3. nagios-解决监控页面上的乱码

    1. 前景 在nagios的监控页面上发现返回来的信息为乱码,如下图所示: 查看相关日志,发现正常显示汉字,如下: 2. 解决方法(以下两个步骤缺一不可) 主要原因分析如下: 在nagios服务器上发 ...

  4. Lucene 入门需要了解的东西

    全文搜索引擎的原理网上大段的内容,要想深入的学习,最好的办法就是先用一下,lucene 发展比较快,下面是写第一个demo  要注意的一些事情: 1.Lucene的核心jar包,下面几个包分别位于不同 ...

  5. PHP中mysql_affected_rows()和mysql_num_rows()区别

    mysql_affected_rows -- 取得前一次 MySQL 操作所影响的记录行数mysql_num_rows -- 函数返回结果集中行的数目. config.php <?php hea ...

  6. STL源码剖析读书笔记--第6章&第7章--算法与仿函数

    老实说,这两章内容还蛮多的,但是其实在应用中一点点了解比较好.所以我决定这两张在以后使用过程中零零散散地总结,这个时候就说些基本概念好了.实际上,这两个STL组件都及其重要,我不详述一方面是自己偷懒, ...

  7. Best Practices for Speeding Up Your Web Site

    The Exceptional Performance team has identified a number of best practices for making web pages fast ...

  8. HDU ACM 1050 Moving Tables

    Problem Description The famous ACM (Advanced Computer Maker) Company has rented a floor of a buildin ...

  9. Cocos2d-JS v3.0 alpha 导入 cocostudio的ui配置

    1.在新项目的根文件夹下打开project.json文件,修改: "modules" : ["cocos2d", "extensions", ...

  10. 第三百五十八天 how can I 坚持

    万事要有度,不要话唠,也不能不说,把握好分寸,今天貌似又说多了. 加了天班,理了个发,还有老爸明天来北京. 还有同学聚会没去,还有金龙让去吃鱼,没去. 还有.小米视频通话还行,能远程控制桌面, 还有, ...