简体   繁体   English

如何更改富文本框中第一个索引处出现的字母的颜色?

[英]How to change the color of letter present at first index in rich textbox?

I am trying to change the color of letter present at first index in rich textbox. 我正在尝试更改富文本框中第一个索引处出现的字母的颜色。 But my code is not working. 但是我的代码无法正常工作。 I am using getpositionatoffset form 0 index to 1, Here is my code : 我正在使用getpositionatoffset形式0索引到1,这是我的代码:

C# C#

TextSelection ts = box1.Selection;
TextPointer tp = box1.Document.ContentStart.GetPositionAtOffset(0);
TextPointer tpe = box1.Document.ContentStart.GetPositionAtOffset(1);
ts.Select(tp, tpe);
ts.ApplyPropertyValue(TextElement.ForegroundProperty, new  SolidColorBrush(Colors.Red));

If I change the value of GetPositionAtOffset(1) to GetPositionAtOffset(3) It will start working. 如果我将GetPositionAtOffset(1)的值更改为GetPositionAtOffset(3),它将开始工作。 I don't why it is happening. 我不知道为什么会这样。

XAML : XAML:

<RichTextBox   Name="box1" Grid.ColumnSpan="2">
        <FlowDocument Name="flowdoc">
            <Paragraph Name="para" >I am a flow document. Would you like to edit me?</Paragraph>
        </FlowDocument>
</RichTextBox>

Your document contains more than text. 您的文档不仅仅包含文本。 There are FlowDocument and Paragraph. 有FlowDocument和Paragraph。 So GetPositionAtOffset(0) returns the flowdocument opening instead of the first letter. 因此, GetPositionAtOffset(0)返回流文档的开头而不是第一个字母。 To get the first character you must move forward until you find a text element: 要获得第一个字符,您必须继续前进,直到找到文本元素为止:

TextPointer position = box1.Document.ContentStart;
while (position != null)
{
    if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
    {
        TextPointer start = position.GetPositionAtOffset(0, LogicalDirection.Forward);
        TextPointer end = position.GetPositionAtOffset(1, LogicalDirection.Backward);
        new TextRange(start, end).ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
        break;
    }
    position = position.GetNextContextPosition(LogicalDirection.Forward);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM