在C#中的RichtextBox中给文本着色

6
我该如何将一些不同颜色的新文本行添加到RichTextBox中?我正在使用SilverLight。
1个回答

2

您可以在代码中进行此操作:

    // 创建一个带有两个颜色运行的段落
    Paragraph para = new Paragraph();
    Run run1 = new Run("Red ");
    run1.Foreground = Brushes.Red;
    Run run2 = new Run("Green");
    run2.Foreground = Brushes.Green;
    para.Inlines.Add(run1);
    para.Inlines.Add(run2);
    // 获取文档
    FlowDocument doc = richTextBox1.Document;
    // 清除现有内容
    doc.Blocks.Clear();
    // 添加新内容
    doc.Blocks.Add(para);

或者在XAML中:

    <RichTextBox Height="160" HorizontalAlignment="Left" Margin="43,20,0,0" Name="richTextBox1" VerticalAlignment="Top" Width="258" TextChanged="richTextBox1_TextChanged">
        <FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
            <Paragraph>
                <Run Foreground="Red">Red</Run>
                <Run Foreground="Green">Green</Run>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接