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

转载于:https://www.cnblogs.com/xiefang2008/p/5961897.html

WPF RichTextBox 控件常用方法和属性相关推荐

  1. WinForm中使用WPF的控件

    在WinForm中可以使用WPF中的控件,或者由WPF创建的自定义控件: 步骤1:创建WinForm工程: 步骤2:在WinForm工程的解决方案资源管理器中,在刚刚创建的WinForm解决方案中新建 ...

  2. WinForm如何使用WPF的控件

    在WinForm中可以使用WPF中的控件,或者由WPF创建的自定义控件: 步骤1:创建WinForm工程: 步骤2:在WinForm工程的解决方案资源管理器中,在刚刚创建的WinForm解决方案中新建 ...

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

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

  4. C#控件及常用属性整理

    C#控件一览表 前所未有的震撼(太详细了) 1.窗体 1.常用属性 (1)Name属性:用来获取或设置窗体的名称,在应用程序中可通过Name属性来引用窗体. (2) WindowState属性: 用来 ...

  5. 第二章:WPF常用控件介绍

    前言 总目录 在上一章中,初步的认识了WPF,那么这一章将逐个的认识一些常用的控件以及这些控件的常用属性,这对于我们我们后续开发WPF程序是非常有必要的. 一.Window窗体 1.Window基本用 ...

  6. WPF 表格控件 ReoGrid 的简单使用

    WPF 表格控件 ReoGrid 的简单使用 目录 一.概述 二.安装 三.添加控件 四.加载 Excel 五.属性设置 六.支持触摸滚动 七.其它操作 1.显示和隐藏列 2.显示特定字体 八.资源链 ...

  7. OxyPlot.Wpf 图表控件使用备忘

    OxyPlot.Wpf 图表控件使用备忘 目录 OxyPlot.Wpf 图表控件使用备忘 一.OxyPlot.Wpf 控件信息 二.基本概念 (一) PlotView 和 Plot (二) PlotM ...

  8. 【转】WPF默认控件模板的获取和资源词典的使用

    一.获取默认的控件模板 WPF修改控件模板是修改外观最方便的方式,但是会出现不知道原来的控件的模板长什么样,或者如何在原有控件模板上修改的,下面就分享了获取某控件默认控件模板的方法(以控件Button ...

  9. C#入门学习-----图书阅读器(WPF 用户控件技术)

    欢迎大家提出意见,一起讨论! 转载请标明是引用于 http://blog.csdn.net/chenyujing1234 需要源码请与我联系. 编译平台:VS2008 + .Net Framework ...

最新文章

  1. 修改mysql的root密码
  2. 从2019年-2021年的各大顶会论文,看动态神经网络的发展
  3. python之路day4_python之路day4
  4. SQLSERVER存储过程列名无效的解决方法
  5. cordova开发日记04 常用插件与使用(更新2016-05-19)
  6. 苹果汽车真是全自动驾驶?分析师称不要指望有方向盘
  7. mysql c测试程序_MySQL · 最佳实践 · 一个TPC-C测试工具sqlbench使用-阿里云开发者社区...
  8. 二叉搜索树前序序列转中序和后序
  9. dell t640 添加硬盘_Dell EMC PowerEdge T640详解
  10. 取出字符串中数字的最大值
  11. perl linux yum,Linux CentOS6.5(x86_64)安装Perl5.26
  12. 良心!不限速2T大容量!阿里Teambition网盘体验~~~
  13. (FAQ)VM log是做什么的,4 Way VM又是什么
  14. 技术总监/技术leader职责与工作记录第一天
  15. 消息中间件架构面面观
  16. android底层 考试 华清,Android开发架构你真的了解吗—华清创客学院
  17. 术语-BPM:BPM
  18. 【人工智能】Rutgers大学熊辉教授:《易经》如何指导我们做人工智能;这里有一篇深度强化学习劝退文
  19. 在 Linux 上烧录 CD
  20. AE484 3D大气电影风格LOGO视频片头爆炸烟雾粒子碎片特效动画制作ae模板

热门文章

  1. matlab快速将几幅图片放在一幅图片
  2. [java]内部类的总结
  3. Java判断100到200之间所有的素数,并且输出这些素数
  4. Python爬虫编程实践 Task04
  5. 从RCNN到SSD,深度学习目标检测算法盘点
  6. 基于评论、新闻的情感倾向分析作商品的价格预测
  7. linux系统与linux内核,[科普] Linux 的内核与 Linux 系统之间的关系
  8. mysql 事务处理null_如何使用Mysql正确的处理财务数据
  9. python中datetime函数怎么获得当年年份_Python 日期和时间函数使用指南
  10. 主板没有rgb接口怎么接灯_电脑硬件第六期,关于主板的那点破事。