RichtextBox中的着色文本,C#

时间:2010-09-21 15:59:49

标签: c# silverlight richtextbox

如何使用不同颜色为新文本行着色,然后将其添加到RichTextBox? 我正在使用SilverLight。

1 个答案:

答案 0 :(得分:2)

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

    // Create a paragraph with two coloured runs
    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);
    // Get the document
    FlowDocument doc = richTextBox1.Document;
    // Clear existing content
    doc.Blocks.Clear();
    // Add new content
    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>