Reputation: 3843
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 :
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. I don't why it is happening.
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>
Upvotes: 0
Views: 736
Reputation: 21337
Your document contains more than text. There are FlowDocument and Paragraph. So GetPositionAtOffset(0)
returns the flowdocument opening instead of the first letter.
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);
}
Upvotes: 6