xaml页面中放置一个RichTextBox,想通过后台的方式添加三段文字,每段文字的颜色各不相同。
如果只是单纯添加文字,那么直接使用TextRange range1 = new TextRange(rtbMessage.Document.ContentStart, rtbMessage.Document.ContentEnd);就可以,如果颜色相同,那么改变ForeGround也就了结了,但是要求颜色不同,并且在后台操作。
请各位大侠不吝赐教。

解决方案 »

  1.   

    XAML我也刚开始学习,希望早点看到答案
      

  2.   

    这个功能是基本功能,莫非WPF根本就没有想到后台可以这样操作?
    如果重写,应该如何实现,请给出有价值的参考代码
      

  3.   

    楼主,关于这个东西,我自己现在也在研究,没有全部研究出来,给个半成品,大家一起研究吧~
    其实做法和以前winform中的是差不多的:
                //add the first message
                TextPointer i = richTextBox1.Document.ContentStart;
                richTextBox1.AppendText("hello!world!" + Environment.NewLine);
                TextPointer j = richTextBox1.Document.ContentEnd;
                TextRange tr = new TextRange(i, j);
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
                // add the second message
                TextPointer m = richTextBox1.Document.ContentEnd;
                richTextBox1.AppendText("good!james!" + Environment.NewLine);
                TextPointer n = richTextBox1.Document.ContentEnd;
                TextRange tr1 = new TextRange(m, n);
                string s = tr1.Text;
                tr1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue); 只是出现的问题在哪呢:以前winform中选择的文本末行的首尾是值类型。而现在的TextPointer 是引用类型。所以用以前的方法是不能通过的。至于如何解决这个问题,还在研究中~~~
      

  4.   

    ok!
    想了一下午,上面发的还是不能解决。
    现在重新换了种方法。
    在设计页面放个richtextbox就行了
    名字改成myRichTextBox。 将代码放入即ok~        // Create a FlowDocument to contain content for the RichTextBox.
                FlowDocument myFlowDoc = new FlowDocument();
                for (int i = 0; i < 5; i++)
                {
                    string s = "hello world " + i.ToString() + Environment.NewLine;
                    // Create a Run of plain text and some bold text.
                    Run myRun = new Run(s);
                    if (i % 2 == 0)
                    {
                        myRun.Foreground = Brushes.Red;
                    }
                    else
                    {
                        myRun.Foreground = Brushes.Green;
                    }
                    // Create a paragraph and add the Run and Bold to it.
                    Paragraph myParagraph = new Paragraph();
                    myParagraph.Inlines.Add(myRun);                               // Add the paragraph to the FlowDocument.
                    myFlowDoc.Blocks.Add(myParagraph);                                // Add initial content to the RichTextBox.
                    myRichTextBox.Document = myFlowDoc;希望能对你有帮助~~~
      

  5.   

    是这样的 最好不要添加一些偏门的类型,最好加入一些熟悉的组件,比如:TextBlock
      加入3个TextBlock 然后分别设置前景色岂可。