WPF RichTextBox 控件常用方法和属性
以下内容转自 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 控件常用方法和属性的更多相关文章
- WPF系列 —— 控件添加依赖属性(转)
WPF系列 —— 控件添加依赖属性 依赖属性的概念,用途 ,如何新建与使用.本文用做一个自定义TimePicker控件来演示WPF的依赖属性的简单应用. 先上TimePicker的一个效果图. 概念 ...
- [WPF]Slider控件常用方法
WPF的Slider控件继承自RangeBase类型,同继承自RangeBase的控件还有ProgressBar和ScrollBar,这类控件都是在一定数值范围内表示一个值的用途. 首先注意而Rang ...
- WPF系列 —— 控件添加依赖属性
依赖属性的概念,用途 ,如何新建与使用.本文用做一个自定义TimePicker控件来演示WPF的依赖属性的简单应用. 先上TimePicker的一个效果图. 概念 和 用途:依赖属性是对传统.net ...
- WPF Image控件的Source属性是一个ImageSource对象
1.固定的图片路径是可以的,如下: <Image Source="../test.png" /> 2.绑定的Path是一个String类型的图片路径,而实际情况它需要的 ...
- WPF 用户控件的自定义依赖属性在 MVVM 模式下的使用备忘
依赖属性相当于扩充了 WPF 标签的原有属性列表,并可以使用 WPF 的绑定功能,可谓是十分方便的:用户控件则相当于代码重用的一种方式:以上几点分开来还是比较好理解的,不过要用到MVVM 模式中,还是 ...
- 设置RichTextBox控件的文本的对齐方式
实现效果: 知识运用: RichTextBox控件的SelectionAlignment属性 //获取或设置在当前选择或插入点的对齐方式 public HorizontalAlignment Sele ...
- 在RichTextBox控件中替换文本文字
实现效果: 知识运用: RichTextBox控件的SelectedText属性 实现代码: private void button1_Click(object sender, EventArgs e ...
- WPF布局控件与子控件的HorizontalAlignment/VerticalAlignment属性之间的关系
WPF布局控件与子控件的HorizontalAlignment/VerticalAlignment属性之间的关系: 1.Canvas/WrapPanel控件: 其子控件的HorizontalAlign ...
- 【转】WPF中PasswordBox控件的Password属性的数据绑定
英文原文:http://www.wpftutorial.net/PasswordBox.html 中文原文:http://blog.csdn.net/oyi319/article/details/65 ...
随机推荐
- linux下valgrind的使用概述
Valgrind简介: Valgrind是动态分析工具的框架.有很多Valgrind工具可以自动的检测许多内存管理和多进程/线程的bugs,在细节上剖析你的程序.你也可以利用Valgrind框架来实现 ...
- 搭建XMPP协议,实现自主推送消息到手机
关于服务器端向Android客户端的推送,主要有三种方式: 1.客户端定时去服务端取或者保持一个长Socket,从本质讲这个不叫推送,这是去服务端拽数据.但是实现简单,主要缺点:耗电等 2.Googl ...
- EditText 光标不显示问题
android:textCursorDrawable="@drawable/bg_txt_cursor" <?xml version="1.0" enco ...
- loadrunner下检查点乱码情况处理
对于很多用过LR的人来说,乱码一直是很纠结的事情,尤其是对新手来说.网上给的解决方法是在录制的时候勾选UTF-8选项,但是似乎并没有解决. 对于用户名为中文或者检查点为中文的情况,我们又该如何去处理呢 ...
- eclipse 编辑器的使用
随着所编辑的文件数目的增加以及在这些文件之间的快速切换,一个又一个文件的编码以及对编辑器会话(session)的管理将会变得非常复杂.这时,有几件事情你是可以做的. 通过使用键盘快捷键,你可以快速选择 ...
- Go语言相关图书推荐
Go语言编程 作 者 许式伟 等 著 出 版 社 人民邮电出版社 出版时间 2012-08-01 版 次 1 页 数 245 印刷时间 2012-08-01 开 ...
- webservice注释
@WebService 1.serviceName: 对外发布的服务名,指定 Web Service 的服务名称:wsdl:service.缺省值为 Java 类的简单名称 + Service.(字符 ...
- Array.prototype.slice.call
Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组 ,::'age'}; Array.prototype.slice.call(arr); ...
- HDU2648:Shopping(DKBR_hash)
题目链接 题意: 给出n个字符串,接下来m天,每天每个字符串要增加对应的值,询问“memory”每天的排名 分析: 用hash表hash出每个字符串对应得值,然后放入二维数组(防止地址冲突),m天,输 ...
- 阿里云存储OSS之九大使用技巧
http://www.biphp.com/cloud-computing/%E9%98%BF%E9%87%8C%E4%BA%91%E5%AD%98%E5%82%A8oss%E4%B9%8B%E4%B9 ...