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中的地位 程序的本质是数据+算法.数据会在 ...
随机推荐
- Go语言获取本地IP地址
最近要做一个向局域网内的所有设备广播发送信息,并接受设备的回复信息,回复信息包括设备的版本号,IP地址,运行工程名等信息.发现一个局域网内是可以有不同的网段的,但UDP广播只能是同一个网段的广播.又发 ...
- atoi 和 atof (把数字字符串转化为数字储存)
int atoi(char *s) 如果字符串内容是整数就返回该整数,否则返回0 double atof(char *s) 同上,不过返回浮点型 #include<iostream> #i ...
- 【SAPUI5】ODataを構成するもの
はじめに SAPUI5でアプリケーションを作るにあたり.ODataは避けては通れないトピックです.結構広いテーマなので.5-7回くらいに分けて書きたいと思います.1回目はODataの概要について説明し ...
- kylin实战系列(一)
kylin实战系列(一) 把之前kylin的实践小结一下,以备以后查看.
- 高德API+.NET解决租房问题(JS相关)
在线地址:58同城品牌公寓高德搜房 Github地址:https://github.com/liguobao/58HouseSearch 知乎专栏(点赞用的):高德API+Python解决租房问题(. ...
- Returning Values from Bash Functions
转自:https://www.linuxjournal.com/content/return-values-bash-functions Bash functions, unlike function ...
- jdk8 新特性stream().map()
1.大写字符串列表 1.1 简单的Java示例将Strings列表转换为大写 TestJava8.java package com.mkyong.java8; import java.util.Arr ...
- 洛谷P1379八数码难题
题目描述 在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字.棋盘中留有一个空格,空格用0来表示.空格周围的棋子可以移到空格中. 要求解的问题是:给出一种初始布局(初始状态)和目标布局(为 ...
- iOS-初识swift
在学习iOS开发之前,先掌握一点swift知识是必要的.note:不论是iOS开发还是编程语言的学习,都应该是迭代.由浅入深的过程,是理论实践相结合的过程. 中文文档 swift3(与swift4稍有 ...
- 21天学习caffe(二)
本文大致记录使用caffe的一次完整流程 Process 1 下载mnist数据集(数据量很小),解压放在data/mnist文件夹中:2 运行create_mnist.sh,生成lmdb格式的数据( ...