Coloring Text in RichtextBox, C#

两盒软妹~` 提交于 2019-12-23 09:24:01

问题


How can I color new line of text with some different colors and then add it to RichTextBox? I'm using SilverLight.


回答1:


You can do this in code:

    // 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);

Or in 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>


来源:https://stackoverflow.com/questions/3762150/coloring-text-in-richtextbox-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!