xaml页面中放置一个RichTextBox,想通过后台的方式添加三段文字,每段文字的颜色各不相同。
如果只是单纯添加文字,那么直接使用TextRange range1 = new TextRange(rtbMessage.Document.ContentStart, rtbMessage.Document.ContentEnd);就可以,如果颜色相同,那么改变ForeGround也就了结了,但是要求颜色不同,并且在后台操作。
请各位大侠不吝赐教。
如果只是单纯添加文字,那么直接使用TextRange range1 = new TextRange(rtbMessage.Document.ContentStart, rtbMessage.Document.ContentEnd);就可以,如果颜色相同,那么改变ForeGround也就了结了,但是要求颜色不同,并且在后台操作。
请各位大侠不吝赐教。
如果重写,应该如何实现,请给出有价值的参考代码
其实做法和以前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 是引用类型。所以用以前的方法是不能通过的。至于如何解决这个问题,还在研究中~~~
想了一下午,上面发的还是不能解决。
现在重新换了种方法。
在设计页面放个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;希望能对你有帮助~~~
加入3个TextBlock 然后分别设置前景色岂可。