Select Range of Text in WPF RichTextBox (FlowDocument) Programmatically Select Range of Text in WPF RichTextBox (FlowDocument) Programmatically wpf wpf

Select Range of Text in WPF RichTextBox (FlowDocument) Programmatically


Public Function GoToPoint(ByVal start As TextPointer, ByVal x As Integer) As TextPointer    Dim out As TextPointer = start    Dim i As Integer = 0    Do While i < x        If out.GetPointerContext(LogicalDirection.Backward) = TextPointerContext.Text Or _             out.GetPointerContext(LogicalDirection.Backward) = TextPointerContext.None Then            i += 1        End If        If out.GetPositionAtOffset(1, LogicalDirection.Forward) Is Nothing Then            Return out        Else            out = out.GetPositionAtOffset(1, LogicalDirection.Forward)        End If    Loop    Return outEnd Function

Try this, this should return a text pointer for the given char offset. (Sorry its in VB, but thats what I am working in...)


Try that :

var textRange = MyRichTextBox.Selection;var start = MyRichTextBox.Document.ContentStart;var startPos = start.GetPositionAtOffset(3);var endPos = start.GetPositionAtOffset(8);textRange.Select(startPos, endPos);textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);


I tried using the solution posted by KratzVB but found that it was ignoring newlines. If you want to count \r and \n symbols then this code should work:

private static TextPointer GetPoint(TextPointer start, int x){        var ret = start;        var i = 0;        while (ret != null)        {            string stringSoFar = new TextRange(ret, ret.GetPositionAtOffset(i, LogicalDirection.Forward)).Text;            if (stringSoFar.Length == x)                    break;            i++;            if (ret.GetPositionAtOffset(i, LogicalDirection.Forward) == null)                return ret.GetPositionAtOffset(i-1, LogicalDirection.Forward)        }        ret=ret.GetPositionAtOffset(i, LogicalDirection.Forward);        return ret;}