Binding and styling text to a RichTextBox in WPF
http://www.codeproject.com/Articles/137209/Binding-and-styling-text-to-a-RichTextBox-in-WPF
The RichTextBox in WPF is a great tool for dealing with text that needs to be styled (such as syntax highlighting) but it's not so great when it comes to allowing us to bind and edit text on the fly.
I got a feature request from our product manager to change the colour of certain text within a TextBox to match a legacy application. It turns out it is not as straight forward as you might expect.
We have text in an SQL database like this:
Collapse | Copy Codethis is a title:.\r\n\r\nThis is a normal line\r\n\r\nthis is another title:.\r\n
You can see that the titles end with “:.” so all we need to do is pull out these lines and make them (in my case) blue.
The problem is that this text is on an object that my previous TextBox was able to bind its Text property to with ease, but the RichTextBox has no text property as it displays a flow document. OK, I thought, I will just bind thetext to the document as follows:
Collapse | Copy Code<RichTextBox IsReadOnly=”True” Document=”{Binding ElementName=ViewType,
Path=SelectedItem.Tag />
This doesn't work because the Document property is not a Dependency Property and therefore cannot be bound to. So BindableRichTextBox here I come. I created a very simple control so that I could bind to the Documentproperty. In doing this, I discovered that the Document property expects a FlowDocument as its content so I had to convert my text string to a flow document with the relevant parts highlighted. I used a converter to spit out theFlowDocument with the correctly formatted text on a per line basis.
Collapse | Copy Codepublic object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
FlowDocument doc = new FlowDocument(); string s = value as string;
if (s != null)
{
using (StringReader reader = new StringReader(s))
{
string newLine;
while ((newLine = reader.ReadLine()) != null)
{
Paragraph paragraph = null;
if (newLine.EndsWith(":."))
{
paragraph = new Paragraph
(new Run(newLine.Replace(":.", string.Empty)));
paragraph.Foreground = new SolidColorBrush(Colors.Blue);
paragraph.FontWeight = FontWeights.Bold;
}
else
{
paragraph = new Paragraph(new Run(newLine));
} doc.Blocks.Add(paragraph);
}
}
} return doc;
}
This simply takes the string and reads it line by line. If we have the desired characters at the end of a line (“:.”), then we make the line blue and bold and remove the characters, otherwise we just add the text. Each line is added as a paragraph so to reduce the space between each one I added the following to the control declaration in the XAML:
Collapse | Copy Code<RichTextBox.Resources>
<Style TargetType=”{x:Type Paragraph}”>
<Setter Property=”Margin” Value=”0?/>
</Style>
</RichTextBox.Resources>
This simply removes the margin from each paragraph.
The final part of the puzzle is the control that allows binding. This is a simple case of adding a dependency property onto a new control that inherits from RichTextBox.
Collapse | Copy Codepublic class BindableRichTextBox : RichTextBox
{
public static readonly DependencyProperty DocumentProperty =
DependencyProperty.Register("Document", typeof(FlowDocument),
typeof(BindableRichTextBox), new FrameworkPropertyMetadata
(null, new PropertyChangedCallback(OnDocumentChanged))); public new FlowDocument Document
{
get
{
return (FlowDocument)this.GetValue(DocumentProperty);
} set
{
this.SetValue(DocumentProperty, value);
}
} public static void OnDocumentChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
RichTextBox rtb = (RichTextBox)obj;
rtb.Document = (FlowDocument)args.NewValue;
}
}
I hope you find a use for this – I simply need it written down somewhere so I don't forget!
Binding and styling text to a RichTextBox in WPF的更多相关文章
- 同时使用Binding&StringFormat 显示Text【项目】
Case ID (?unit) 红色的字根据一个后台boolean来做trigger,可以是Case or Open 蓝色的字binding到后台的一个string属性来切换任意的Unit单位 这样一 ...
- 附3:tips of layout binding and styling
1. how to clear content of ng-model in controller? 如何在conroller中清除ng-model绑定的内容? .state('tab.login', ...
- Insert Plain Text and Images into RichTextBox at Runtime
Insert Plain Text and Images into RichTextBox at Runtime' https://www.codeproject.com/Articles/4544/ ...
- WPF RichTextBox相关总结
由于公司涉及到聊天对话框的功能,就想到了RichTextBox,查阅相关资料,总结下: 一.RichTextBox的内容相关的类 1.1RichTextBox的内容结构 RichTexBox是个可编辑 ...
- 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令
[源码下载] 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令 作者:webabcd ...
- 背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令
[源码下载] 背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令 作者:webabcd ...
- 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合
[源码下载] 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合 作 ...
- TRichTextBox – A universal RichTextBox which can display animated images and more
TRichTextBox – A universal RichTextBox which can display animated images and more trestan, 7 Dec 201 ...
- WPF之Binding深入探讨
原文:http://blog.csdn.net/fwj380891124/article/details/8107646 1,Data Binding在WPF中的地位 程序的本质是数据+算法.数据会在 ...
随机推荐
- python2.7练习小例子(十六)
16):题目:输入一行字符,分别统计出其中英文字母.空格.数字和其它字符的个数. 程序分析:利用 while 或 for 语句,条件为输入的字符不为 '\n'. 程序源代码: #!/u ...
- Xshell启动时显示丢失MSVCP110.dll解决方法
成功安装xshell之后,在运行时却弹出“无法启动此程序,因为计算机中丢失MSVCP110.dll.尝试重新安装该程序以解决此问题”,很多人按照提示重装了还是出现同样的问题,本集教程将具体讲解如何处理 ...
- MVC中Model 的Key值不建议用非int型
一次在开发中,key的值用了 byte型,结果插入第一条正常,第二条开始就出错,原因是用byte类型无法实现自动增加1,所以为了方便,建议使用 int型. public virtual byte bk ...
- c/c++ 随机数生成
当程序需要一个随机数时有两种情况下使用: 1.程序中只需使用一次随机数,则调用rand()函数即可 2.程序需要多次使用随机数,那么需要使用srand()函数生成随机数种子在调用rand()函数保证每 ...
- LeetCode:22. Generate Parentheses(Medium)
1. 原题链接 https://leetcode.com/problems/generate-parentheses/description/ 2. 题目要求 给出一个正整数n,请求出由n对合法的圆括 ...
- 类的__new__方法使用
class Person(object): def __init__(self): self.name ="aaa" def defineName(self): self.name ...
- L009文件属性知识详解小节
本堂课分为5部分内容 1.linux下重要目录详解 2.PATH变量路径内容 3.linux系统中文件类型介绍 4.linux系统中文件属性详细介绍 5.linux系统文件属性inode与block知 ...
- 一步一步构建手机WebApp开发——页面布局篇
继上一篇:一步一步构建手机WebApp开发——环境搭建篇过后,我相信很多朋友都想看看实战案例,这一次的教程是页面布局篇,先上图: 如上图所示,此篇教程便是教初学者如何快速布局这样的页面.废话少说,直接 ...
- Annoy解析
Annoy是高维空间求近似最近邻的一个开源库. Annoy构建一棵二叉树,查询时间为O(logn). Annoy通过随机挑选两个点,并使用垂直于这个点的等距离超平面将集合划分为两部分. 如图所示,图中 ...
- truffle开发一个简单的Dapp
1.安装Truffle:npm install -g truffle 2.建立项目目录并进入:mkdir pet-shop-tutorial cd pet-shop-tutorial 3.使用truf ...