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

dan*_*mad 0 .net c# wpf xaml

我正在尝试更改富文本框中第一个索引处出现的字母的颜色.但我的代码不起作用.我使用getpositionatoffset表格0索引为1,这是我的代码:

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));
Run Code Online (Sandbox Code Playgroud)

如果我将GetPositionAtOffset(1)的值更改为GetPositionAtOffset(3)它将开始工作.我不知道为什么会这样.

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>
Run Code Online (Sandbox Code Playgroud)

mez*_*tou 6

您的文档不仅包含文字.有FlowDocument和Paragraph.因此GetPositionAtOffset(0)返回flowdocument开头而不是第一个字母.要获得第一个字符,您必须继续前进,直到找到文本元素:

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);
}
Run Code Online (Sandbox Code Playgroud)