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 Code
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:

 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 Code
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:

 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 Code
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的更多相关文章

  1. 同时使用Binding&StringFormat 显示Text【项目】

    Case ID (?unit) 红色的字根据一个后台boolean来做trigger,可以是Case or Open 蓝色的字binding到后台的一个string属性来切换任意的Unit单位 这样一 ...

  2. 附3:tips of layout binding and styling

    1. how to clear content of ng-model in controller? 如何在conroller中清除ng-model绑定的内容? .state('tab.login', ...

  3. Insert Plain Text and Images into RichTextBox at Runtime

    Insert Plain Text and Images into RichTextBox at Runtime' https://www.codeproject.com/Articles/4544/ ...

  4. WPF RichTextBox相关总结

    由于公司涉及到聊天对话框的功能,就想到了RichTextBox,查阅相关资料,总结下: 一.RichTextBox的内容相关的类 1.1RichTextBox的内容结构 RichTexBox是个可编辑 ...

  5. 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令

    [源码下载] 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令 作者:webabcd ...

  6. 背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令

    [源码下载] 背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令 作者:webabcd ...

  7. 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合

    [源码下载] 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合 作 ...

  8. 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 ...

  9. WPF之Binding深入探讨

    原文:http://blog.csdn.net/fwj380891124/article/details/8107646 1,Data Binding在WPF中的地位 程序的本质是数据+算法.数据会在 ...

随机推荐

  1. WPF中使用定时器的注意事项

    原文:WPF中使用定时器的注意事项 注意事项 要使用System.Windows.Threading.DispatcherTimer,而不能使用System.Timers.Timer. 原因是WPF是 ...

  2. MUI:字符串和json数据的相互转换

    JSON.parse()--字符串转换json.JSON.stringify()--json转换成字符串 如:收到Json对象:response,则: {"result":&quo ...

  3. Python正则反向引用

    str2 ="2018-10-29"c =re.sub(r"(\d{4})-(\d{2})-(\d{2})","\g<1>/\g<2 ...

  4. How to enable download EXE files from the Sharepoint website

          As we all know,many applications have forbidden to upload and download exe files.Because the e ...

  5. 用jsp实现省市区三级联动下拉

    jsp+jquery实现省市区三级联动下拉 不少系统都需要实现省市区三级联动下拉,像人口信息管理.电子商务网站.会员管理等,都需要填写地址相关信息.而用ajax实现的无刷新省市区三级联动下拉则可以改善 ...

  6. Go基础篇【第4篇】: 内置库模块 bufio

    bufio包实现了有缓冲的I/O.它包装一个io.Reader或io.Writer接口对象,创建另一个也实现了该接口,且同时还提供了缓冲和一些文本I/O的帮助函数的对象. 即:为了解决CPU与磁盘IO ...

  7. 第5讲——cin处理字符输入

    本来这一讲应该是while.for.if之类的,但是,我们可是学过C的男人,再浪费时间搞这个??? 还不如学点C++中的新知识. cin对象支持3种不同模式的单字符输入,其用户接口各不相同. 下面我们 ...

  8. 最大流——EK算法

    一.算法理论 [基本思想] 反复寻找源点s到汇点t之间的增广路径,若有,找出增广路径上每一段[容量-流量]的最小值delta,若无,则结束.在寻找增广路径时,可以用BFS来找,并且更新残留网络的值(涉 ...

  9. Spring框架(依赖注入)

    特点 1轻量级和侵入性低 2依赖注入和面向接口实现松耦合 3面向切面编程 减少样式代码 专有名词: 1依赖注入:对象无需自行管理依赖关系.通过系统负责协调在创建对象的第三方组件的设定,实现依赖关系自动 ...

  10. SQL select 和SQL where语句

    一.SQL SELECT语句 用于从表中选取数据,结果被存储在一共结果表中(称为结果集) 1.语法: SELECT 列名称   FROM  表名称 以及: SELECT * FROM 表名称 注:SQ ...