You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WPF RichTextBox中设置部分文本的粗体与不同字体样式

WPF RichTextBox 动态格式化文本实现方案

问题根源

直接绑定纯文本到Run的Text属性时,WPF不会解析其中的XML格式标签(比如<Bold>),因为Run仅处理纯文本内容。要实现带格式的显示,需要让RichTextBox加载带格式的FlowDocument,而非纯字符串。

方案一:用值转换器将格式化XAML字符串转为FlowDocument

这种方案完全符合你的需求:只需给SampleText赋值带XAML格式的字符串,即可自动在界面显示对应格式。

1. 创建值转换器

using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Xml;

public class XamlToFlowDocumentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is string xamlString && !string.IsNullOrEmpty(xamlString))
        {
            try
            {
                var flowDocument = new FlowDocument();
                var xmlReader = XmlReader.Create(new System.IO.StringReader(xamlString));
                var paragraph = (Paragraph)System.Windows.Markup.XamlReader.Load(xmlReader);
                flowDocument.Blocks.Add(paragraph);
                return flowDocument;
            }
            catch
            {
                // 转换失败时返回包含原文本的默认文档
                return new FlowDocument(new Paragraph(new Run(xamlString)));
            }
        }
        return new FlowDocument();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

2. XAML中配置绑定

先在窗口资源中声明转换器:

<Window.Resources>
    <local:XamlToFlowDocumentConverter x:Key="XamlToFlowDocConverter"/>
</Window.Resources>

修改RichTextBox的绑定逻辑:

<RichTextBox IsReadOnly="True"
             Focusable="False"
             Document="{Binding SampleText, Converter={StaticResource XamlToFlowDocConverter}}"/>

3. ViewModel中赋值格式化文本

给SampleText赋值包含格式的XAML片段即可:

SampleText = @"<Paragraph FontFamily='Segoe UI'>
                    <Run FontSize='16' FontWeight='Bold'>Lorem ipsum</Run> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor <Bold>in reprehenderit</Bold> in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </Paragraph>";

方案二:直接在ViewModel中构建FlowDocument(更灵活)

如果不想用XAML字符串,也可以直接在ViewModel中创建FlowDocument对象并绑定。

1. ViewModel中定义属性

private FlowDocument _formattedText;
public FlowDocument FormattedText
{
    get => _formattedText;
    set
    {
        _formattedText = value;
        OnPropertyChanged(); // 确保ViewModel实现了INotifyPropertyChanged接口
    }
}

2. 构建带格式的FlowDocument

var doc = new FlowDocument();
var paragraph = new Paragraph { FontFamily = new System.Windows.Media.FontFamily("Segoe UI") };

// 首个短语:大字号+加粗
var firstRun = new Run("Lorem ipsum ") { FontSize = 16, FontWeight = FontWeights.Bold };
paragraph.Inlines.Add(firstRun);

// 普通文本部分
var normalRun1 = new Run("dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor ");
paragraph.Inlines.Add(normalRun1);

// 加粗文本部分
var boldRun = new Run("in reprehenderit") { FontWeight = FontWeights.Bold };
paragraph.Inlines.Add(boldRun);

// 剩余普通文本
var normalRun2 = new Run(" in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
paragraph.Inlines.Add(normalRun2);

doc.Blocks.Add(paragraph);
FormattedText = doc;

3. XAML绑定

<RichTextBox IsReadOnly="True"
             Focusable="False"
             Document="{Binding FormattedText}"/>

关键说明

  • 方案一更贴合你的需求:无需在ViewModel中处理复杂的FlowDocument对象,只需维护带格式的XAML字符串即可。
  • 注意XAML字符串的格式正确性,标签需闭合、属性值需加引号,避免转换失败。
  • 两种方案都要求ViewModel实现INotifyPropertyChanged接口,确保属性变更时UI自动更新。

内容的提问来源于stack exchange,提问作者Willy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:10:23