如何在WPF的DataGrid内置RichTextBox中为选中的指定文本设置加粗效果
WPF DataGrid内嵌RichTextBox选中文本加粗实现方案
问题根源
你尝试给文本加标签的方案失效,是因为RichTextBox的Run.Text绑定的是纯字符串,所有输入内容都会被当做普通文本渲染,富文本格式需要通过操作FlowDocument的属性接口实现,不能直接修改纯文本内容插入标签。
核心实现代码
按钮点击事件实现(快速可用)
直接在加粗按钮的点击事件中添加如下代码即可实现选中内容即时加粗:
private void BoldBtn_Click(object sender, RoutedEventArgs e) { // 获取当前聚焦的RichTextBox控件 var currentRichBox = FocusManager.GetFocusedElement(this) as RichTextBox; // 无选中内容时直接返回 if (currentRichBox == null || currentRichBox.Selection.IsEmpty) return; // 给选中区域应用加粗属性 currentRichBox.Selection.ApplyPropertyValue( TextElement.FontWeightProperty, FontWeights.Bold); }
如果需要切换加粗/取消加粗,可以加一层判断:
var currentWeight = currentRichBox.Selection.GetPropertyValue(TextElement.FontWeightProperty); currentRichBox.Selection.ApplyPropertyValue( TextElement.FontWeightProperty, currentWeight is FontWeight weight && weight == FontWeights.Bold ? FontWeights.Normal : FontWeights.Bold);
持久化富文本格式补充说明
你当前的XAML中将Run.Text绑定到纯文本字段desc,只能保存纯文本内容,重启应用或滚动DataGrid后格式会丢失,如果需要持久化富文本格式,需要做如下调整:
- 将数据源中
desc字段改为存储XAML格式的富文本字符串,而非纯文本 - 编写扩展方法实现FlowDocument和XAML字符串的互转:
using System.IO; using System.Text; using System.Windows.Documents; public static class RichTextBoxExtension { // FlowDocument转XAML字符串用于存储 public static string ToXamlString(this FlowDocument doc) { var textRange = new TextRange(doc.ContentStart, doc.ContentEnd); using (var ms = new MemoryStream()) { textRange.Save(ms, DataFormats.Xaml); ms.Position = 0; using (var sr = new StreamReader(ms)) { return sr.ReadToEnd(); } } } // 读取XAML字符串生成FlowDocument用于渲染 public static FlowDocument ToFlowDocument(this string xamlStr) { var doc = new FlowDocument(); var textRange = new TextRange(doc.ContentStart, doc.ContentEnd); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(xamlStr))) { textRange.Load(ms, DataFormats.Xaml); } return doc; } }
- 可以通过附加属性实现RichTextBox的XAML内容绑定,适配MVVM模式,避免后台代码耦合。
内容的提问来源于stack exchange,提问作者mlym
相关产品推荐
相关产品推荐

