WPF RichTextBox,关键字搜索,样式改变,超链接替换,图文混排

RichTextBox 只是一个控件,表示对 FlowDocument 对象执行操作的丰富编辑控件。它所承载的内容由其 Document 属性来呈现。 Document 是一个 FlowDocument 类型. RichTextBox控件允许用户输入和编辑文本的同时提供了比普通的TextBox控件更高级的格式特征。 RichTextBox控件提供了数个有用的特征,你可以在控件中安排文本的格式。要改变文本的格式,必须先选中该文本。只有选中的文本才可以编排字符和段落的格式。有了这些属性,就可以设置文本使用粗体,改变字体的颜色,创建超底稿和子底稿。也可以设置左右缩排或不缩排,从而调整段落的格式。 RichTextBox控件可以打开和保存RTF文件或普通的ASCII文本文件。你可以使用控件的方法(LoadFile和SaveFile)直接读和写文件。RichTextBox控件使用集合支持嵌入的对象。每个嵌入控件中的对象都表示为一个对象。这允许文档中创建的控件可以包含其他控件或文档。例如,可以创建一个包含报表、Microsoft Word文档或任何在系统中注册的其他OLE对象的文档。要在RichTextBox控件中插入对象,可以简单地拖住一个文件(如使用Windows 95的Explorer)或其他应用程序(如Microsoft Word)中所用文件的加亮部分(选择部分),将其直接放到该RichTextBox控件上。RichTextBox控件支持剪贴板和OLE对象的OLE拖放功能。当从剪贴板粘贴对象时,就在当前的插入点插入该对象。如果对象是拖放到控件中,则插入点将跟随鼠标指针位置变动,直到释放开鼠标,然后在鼠标释放处插入对象。要打印RichTextBox控件中的所有或部分文本,使用SelPrint方法。因为RichTextBox控件是数据绑定控件,可以将其与Data控件绑定到Microsoft Access数据库的Binary或Memo数据域,或其他数据库中类似的数据域(如SQL Server中的TEXT数据类型的数据域)。RichTextBox控件支持几乎所有的TextBox控件中的属性、事件和方法,如MaxLength, MultiLine, ScrollBars, SelLength, SelStart和SelText。使用TextBox控件的应用程序很容易改为使用RichTextBox控件。然而,RichTextBox控件并没有普通TextBox控件的64K字符能力的限制。
用法举例:
<RichTextBox Background="#E3E3E3"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
Margin="10,0,0,0"
FontFamily="Microsoft YaHei"
FontSize="12"
IsReadOnly="True"
Foreground="#333333"
x:Name="richTextBox"
BorderThickness="0">
<FlowDocument x:Name="richTextBoxFlowDocument"
LineHeight="20" />
</RichTextBox>
1向文章内容中增加一段文字
public void AddParagraph(string txtCotent)
{
Paragraph p = new Paragraph(); // Paragraph 类似于 html 的 P 标签
Run r = new Run(txtCotent); // Run 是一个 Inline 的标签
p.Inlines.Add(r);
richTextBoxFlowDocument.Blocks.Add(p);
}
2 向文章内容中增加一张图片
public void AddImage(Image imageCotent)
{
Paragraph p = new Paragraph();
InlineUIContainer inline = new InlineUIContainer(imageCotent);
p.Inlines.Add(inline);
richTextBoxFlowDocument.Blocks.Add(p);
}
3 把图片添加到光标位置
private void AddImageInPosin(string filepath)
{
Image img = new Image();
BitmapImage bImg = new BitmapImage();
img.IsEnabled = true;
bImg.BeginInit();
bImg.UriSource = new Uri(filepath, UriKind.Relative);
bImg.EndInit();
img.Source = bImg;
//// 调整图片大小
//if (bImg.Height > 100 || bImg.Width > 100)
//{
// img.Height = bImg.Height * 0.2;
// img.Width = bImg.Width * 0.2;
//}
img.Height = ;
img.Stretch = Stretch.Uniform; //图片缩放模式
new InlineUIContainer(img, richTextBox.Selection.Start); //插入图片到选定位置
}
4 把文章中指定关键字替换成超链接
/// <summary>
/// 设置热点词为超链接
/// </summary>
/// <param name="key">热点词</param>
/// <param name="foreground">热点词字体颜色</param>
public void ConvertKeyToHyperLink(string key, SolidColorBrush foreground)
{
m_TextList = new List<TextRange>();
//设置文字指针为Document初始位置
//richBox.Document.FlowDirection
TextPointer position = richTextBox.Document.ContentStart;
while (position != null)
{
//向前搜索,需要内容为Text
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
//拿出Run的Text
string text = position.GetTextInRun(LogicalDirection.Forward);
//可能包含多个keyword,做遍历查找
int index = ;
index = text.IndexOf(key, );
if (index != -)
{
TextPointer start = position.GetPositionAtOffset(index);
TextPointer end = start.GetPositionAtOffset(key.Length);
// m_TextList.Add(new TextRange(start, end));
linke(new TextRange(start, end), key, foreground);
}
}
//文字指针向前偏移
position = position.GetNextContextPosition(LogicalDirection.Forward);
}
} private void linke(TextRange tp, string key, SolidColorBrush foreground)
{
TextRange tr = new TextRange(tp.Start, tp.End);
Hyperlink hlink = new Hyperlink(tr.Start, tr.End);
hlink.Tag = key;
hlink.Foreground = foreground; hlink.FontFamily = new FontFamily("Microsoft YaHei");
hlink.FontSize = ;
hlink.Cursor = Cursors.Hand;
hlink.MouseDown += hyperlink_MouseDown;
}
5 后台向文章中新增一个超链接
private void AddLink()
{
Hyperlink hyperlink = new Hyperlink();
hyperlink.Foreground = new SolidColorBrush(Colors.Blue);
hyperlink.ForceCursor = true;
hyperlink.Cursor = Cursors.Hand; hyperlink.Inlines.Add("后台添加的超链接");
//hyperlink.NavigateUri = new Uri("http://www.baidu.com",UriKind.Absolute);
hyperlink.MouseDown += hyperlink_MouseDown;
Paragraph p = new Paragraph();
p.Inlines.Add(hyperlink);
richTextBoxFlowDocument.Blocks.Add(p);
}
6 改变用户搜索的关键词的样式,并支持当前选中的高亮
/// <summary>
/// 改变在文章中用户搜索的关键字的字体颜色
/// </summary>
/// <param name="keyword"></param>
public void ChangeSeachKeyWordsColor(string keyword)
{
ChangeColorWithResout(keyword);
} /// <summary>
/// 改变关键字的字体颜色
/// </summary>
/// <param name="keyword">用户搜索关键字</param>
/// <returns></returns>
private List<TextRange> ChangeColorWithResout(string keyword)
{
if (!string.IsNullOrEmpty(m_ProSearchkey))
{
ChangeColor(CommonColorsHelp.DefaultFontColor, m_ProSearchkey);
ReSetBackGroundAll();
}
m_ProSearchkey = keyword; return ChangeColor(CommonColorsHelp.KeyFontColor, keyword);
} /// <summary>
/// 设置背景色
/// </summary>
/// <param name="l"></param>
/// <param name="textRange"></param>
public void SetBackGround(Color l, TextRange textRange)
{
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(l));
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(CommonColorsHelp.SelectedKeyFontColor));
}
/// <summary>
/// 重新设置背景色
/// </summary>
/// <param name="textRange">关键字的的TextRange</param>
/// <param name="isCurrKeyWord">是否是当前的关键字</param>
public void ReSetBackGround(TextRange textRange, bool isCurrKeyWord)
{
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(CommonColorsHelp.DefaultBackGroundColor));
if (isCurrKeyWord)
{
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(CommonColorsHelp.KeyFontColor));
}
else
{
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(CommonColorsHelp.DefaultFontColor));
} } /// <summary>
/// 上一处
/// </summary>
public void SetUpBackGround()
{
if (m_TextList != null && m_TextList.Count > )
{
ReSetBackGround(m_TextList[currNumber], true);
currNumber--;
if (currNumber < )
{
currNumber = m_TextList.Count - ;
}
SetBackGround(CommonColorsHelp.SelectedKeyBackGroundColor, m_TextList[currNumber]);
} }
/// <summary>
/// 下一处
/// </summary>
public void SetDownBackGround()
{
if (m_TextList != null && m_TextList.Count > )
{
ReSetBackGround(m_TextList[currNumber], true);
currNumber++;
if (currNumber >= m_TextList.Count)
{
currNumber = ;
}
SetBackGround(CommonColorsHelp.SelectedKeyBackGroundColor, m_TextList[currNumber]);
}
}
/// <summary>
/// 改变关键字的具体实现
/// </summary>
/// <param name="l"></param>
/// <param name="richTextBox1"></param>
/// <param name="selectLength"></param>
/// <param name="tpStart"></param>
/// <param name="tpEnd"></param>
/// <returns></returns>
private TextPointer selecta(Color l, RichTextBox richTextBox1, int selectLength, TextPointer tpStart, TextPointer tpEnd)
{
TextRange range = richTextBox1.Selection;
range.Select(tpStart, tpEnd);
//高亮选择
range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(l));
return tpEnd.GetNextContextPosition(LogicalDirection.Forward);
}
/// <summary>
/// 把所有背景恢复到默认
/// </summary>
private void ReSetBackGroundAll()
{
if (m_TextList != null)
{
foreach (TextRange textRange in m_TextList)
{
ReSetBackGround(textRange, false);
}
}
}
/// <summary>
/// 当前第几处关键字被选中
/// </summary>
private int currNumber = ;
/// <summary>
/// 改变关键字字体颜色
/// </summary>
/// <param name="l">颜色</param>
/// <param name="keyword">关键字</param>
/// <returns></returns>
private List<TextRange> ChangeColor(Color l, string keyword)
{
m_TextList = new List<TextRange>();
//设置文字指针为Document初始位置
//richBox.Document.FlowDirection
TextPointer position = richTextBox.Document.ContentStart;
while (position != null)
{
//向前搜索,需要内容为Text
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
//拿出Run的Text
string text = position.GetTextInRun(LogicalDirection.Forward);
//可能包含多个keyword,做遍历查找
int index = ;
index = text.IndexOf(keyword, );
if (index != -)
{
TextPointer start = position.GetPositionAtOffset(index);
TextPointer end = start.GetPositionAtOffset(keyword.Length);
m_TextList.Add(new TextRange(start, end));
position = selecta(l, richTextBox, keyword.Length, start, end);
}
}
//文字指针向前偏移
position = position.GetNextContextPosition(LogicalDirection.Forward);
} if (m_TextList != null && m_TextList.Count > )
{
//重置
currNumber = ;
SetBackGround(CommonColorsHelp.SelectedKeyBackGroundColor, m_TextList[currNumber]);
} return m_TextList;
}
/// <summary>
/// 当前关键字共搜索出的结果集合
/// </summary>
private List<TextRange> m_TextList;
WPF RichTextBox,关键字搜索,样式改变,超链接替换,图文混排的更多相关文章
- Unity UGUI图文混排(六) -- 超链接
图文混排更新到超链接这儿,好像也差不多了,不过就在最后一点,博主也表现得相当不专业,直接整合了山中双木林同学提供的超链接的解决方案,博主甚至没来得及细看就直接复制了,但感觉还是挺好用的. 博主已经将超 ...
- WPF使用FlowDocument实现图文混排
代码: <RichTextBox CaretBrush="#fff" Background="Transparent" BorderThickness=& ...
- C#中用RichTextBox实现图文混排和保存的例子
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; us ...
- 【CSS】使用CSS改变超链接样式
超链接代码 <ahrefahref="http://www.divCSS5.com/"target="_blank" title="关于divC ...
- vim文本编辑器——删除、复制、剪切、更改某一个字符、替换、撤销、关键字搜索
1.删除: (1)删除光标所在处的字符: 如上图所示:点击一次x键只能删除一个字符. (2)删除光标所在处后的n个字符(nx): 删除前: 输入6x: (3)删除光标所在的行(dd): 删除前: 输入 ...
- CSS样式表——超链接样式
主要作用是给用HTML做的链接修改样式 主要包括: 1.超链接访问前(被点前)状态a:link 2.超链接访问后(被点后)状态a:visited 3.鼠标指向超链接时(放在上面)状态a:hover 4 ...
- WPF ScrollViewer(滚动条) 自定义样式表制作 图文并茂
原文:WPF ScrollViewer(滚动条) 自定义样式表制作 图文并茂 先上效果图 正常样式 拖动时样式 好下面 开始吧 ==================================== ...
- vue.js(11)--案例--关键字搜索列表
关键字搜索品牌案例 (1)页面布局 <div class="app"> <div class="panel panel-primary"> ...
- iOS13适配/黑暗模式的适配/KVC访问私有属性/模态弹窗ViewController 默认样式改变 /LaunchImage即将废弃/蓝牙的权限申请/推送Device Token适配/UIKit 控件变化/StatusBar新增样式
目录 1. KVC访问私有属性 2. 模态弹窗ViewController 默认样式改变 3. 黑暗模式的适配 4. LaunchImage即将废弃 5. 新增一直使用蓝牙的权限申请 6. Sign ...
随机推荐
- Esfog_UnityShader教程_逐帧动画
有段日子没出这个系列的新文章了,今天就拿一个比较常见也比较基础的利用改变Shader来改变不断调整UV实现播放逐帧动画的小功能.很久没写了就当练练手了.在新版本的Unity中早就已经集成了Sprite ...
- 37. Binary Tree Zigzag Level Order Traversal && Binary Tree Inorder Traversal
Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversa ...
- css兼容问题集合
css兼容问题 兼容问题 1.文字本身的大小不兼容.同样是font-size:14px的宋体文字,在不同浏览器下占的空间是不一样的,ie下实际占高16px,下留白3px,ff下实际占高17px,上留白 ...
- myeclipse自动排版
myeclipse代码排版方式有两种: 1. ctr+f 实现自动排版: 2. myeclipse->Preference->Java->Editor->Sava Action ...
- json和字符串转换
json对象转js字符串 JSON.stringify(json) js字符串转json对象 var json= $.parseJSON(str);
- javascript的replace+正则 实现ES6的字符串模版
采用拼接字符串的形式,将 JSON 数据嵌入 HTML 中.开始时代码量较少,暂时还可以接受.但当页面结构复杂起来后,其弱点开始变得无法忍受起来: 书写不连贯.每写一个变量就要断一下,插入一个 + 和 ...
- CentOS6开启FTP及telnet服务教程
先来开通CentOS6的FTP服务吧.telnet服务也一并学习学习吧.在安装好CentOS以后,需要设置Ftp和Telnet服务文件,才能启动Ftp和Telnet服务,可以通过远程控制进行开启. 开 ...
- Nginx 学习
1.Nginx编译安装 nginx依赖于pcre库,需要先安装pcre(二进制包,跟正则表达式有关),pcre-devel(头文件) configure --prefix=/usr/local/ng ...
- .NET高级工程师面试题之SQL篇
1 题目 这确实是一个真实的面试题,琢磨一下吧!知识不用,就会丢掉,我太依赖各种框架和dll了,已经忘记了最基本的东西.有多久没有写过SQL了,我已经不记得了. 已知表信息如下: Department ...
- linux shell 去掉文本处理中的双引号
cat aa.txt |sed 's/\"//g' 结果是:hello aa.txt "hello"