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. SQL 公用表表达式(CTE)

    1.概念 公用表表达式(Common Table Expression)是SQL SERVER 2005版本之后引入的一个特性.CTE可以看作是一个临时的结果集,可以在接下来的一个SELECT,INS ...

  2. .Net 面试题 汇总(二)

    51..net中读写XML的类都归属于哪些命名空间? 答:System.Xml 52.解释一下UDDI.WSDL的意义及其作用. 答:UDDI即统一描述.发现和集成协议.作用: 用来说明一个Web服务 ...

  3. springmvc 处理put,delete请求

    前言:ajax用post编辑,删除提示越权操作状态为500,修改半晌最后大神指点说是:type修改为post和delete模式 最后还是一知半解,但是程序却正常使用了.当然注意我用的mvc,contr ...

  4. linux mysql root 忘记密码了,完美解决-费元星站长

    修改MySQL的配置文件(默认为/etc/my.cnf),在[mysqld]下添加一行skip-grant-tables   保存配置文件后,重启MySQL服务 service mysqld rest ...

  5. 小程序js脚本模块化调用

    可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块.模块只有通过 module.exports 或者 exports 才能对外暴露接口. 1. common.js // common.j ...

  6. NodeJs命令行新建项目实例

    安装Nodejs: 下载地址:http://nodejs.org/download/ 设置环境变量,例如我将nodejs装在D:/program文件夹下,则设以下为系统环境变量 D:\Program\ ...

  7. MyBatis实例教程--以接口的方式编程

    以接口的方式编程: 只需要修改两个地方即可, 1.mapper.xml(实体类)配置文件, 注意mapper的namespace的名字是mapper对象的完整路径名com.xiamen.mapper. ...

  8. 用OneNote写博客的方法

    1.进入OneNote要发布博客的分区然后点击菜单栏中的文件         2.点击发送至博客         3.这时候会启动word程序弹出下面的对话框(如果你从未设置过)点击立即注册     ...

  9. java线程(2)——模拟生产者与消费者

    前言: 我们都听说过生产者和消费者的例子吧,现在来模拟一下.生产者生产面包,消费者消费面包.假定生产者将生成出来的面包放入篮子中,消费者从篮子中取.这样,当篮子中没有面包时,消费者不能取.当篮子满了以 ...

  10. (转)Nginx配置和内核优化 实现突破十万并发

    nginx指令中的优化(配置文件) worker_processes 8; nginx进程数,建议按照cpu数目来指定,一般为它的倍数. worker_cpu_affinity 00000001 00 ...