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:
this 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:
<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 Document
property. 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.
public 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:
<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
.
public 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中的地位 程序的本质是数据+算法.数据会在 ...
随机推荐
- java入门---windows和Linux,UNIX,Solaris,FreeBSD下开发环境配置
首先来看Windows下的操作.我们需要下载java开发工具包JDK.下载地址:http://www.oracle.com/technetwork/java/javase/downloads/ ...
- gp更新来的太快
意外总是会发生 添加一个判断function的分支,过滤掉function,其实也考虑再进一步去分析它的作用,稍后再议. 更新一下 var gnp = { get: function(url) { r ...
- Linq中dbSet 的查询
1.Find:按照关键字的ID号来查询(速度快) 如: ADShiTi aDShiTi = db.ADShiTis.Find(id); 2.FirstOrDefault:根据部分条件查询,显示最前的一 ...
- 4364: [IOI2014]wall砖墙
4364: [IOI2014]wall砖墙 链接 分析: 线段树,维护一个最大值,一个最小值. 代码: #include<bits/stdc++.h> ],*p1 = buf,*p2 = ...
- easyui combox 随便不存在的值,清空
onHidePanel: function () { var valueField = $(this).combobox("options").valueField; var va ...
- 代码混淆 iOS
该方法只能针对有.m.h的类进行混淆,静态库等只有.h文件的没法进行混淆 代码混淆,刚刚看到是不是有点懵逼,反正我是最近才接触到这么个东西,因为之前对于代码和APP,只需要实现功能就好了,根本没有考虑 ...
- Ubuntu下使用Git_4
在这个第四个文章中,我将练习GIT的高级阶段了,由于高级阶段的内容转的比较多,我自己的代码除了我自己可以看懂意外,大家可能看不懂,所以我将会按照 http://git.wiki.navisec.it/ ...
- ZooKeeper的伪分布式集群搭建
ZooKeeper集群的一些基本概念 zookeeper集群搭建: zk集群,主从节点,心跳机制(选举模式) 配置数据文件 myid 1/2/3 对应 server.1/2/3 通过 zkCli.sh ...
- python中通过string类名获得实例
原文:https://bytes.com/topic/python/answers/42866-how-create-object-instance-string Ksenia Marasanova的 ...
- Java 中的异常和处理详解(转载)
原文出处: 代码钢琴家 简介 程序运行时,发生的不被期望的事件,它阻止了程序按照程序员的预期正常执行,这就是异常.异常发生时,是任程序自生自灭,立刻退出终止,还是输出错误给用户?或者用C语言风格:用函 ...