Search code examples
c#xamluwpuwp-xamlricheditbox

UWP RichEditBox equivalent of GetCharIndexFromPosition


It seems like the GetCharIndexFromPosition is missing in UWP's richeditbox. I want to display a tooltip when a certain range is hovered over in a RichEditBox. Is this possible with UWP?


Solution

  • In UWP, we can use GetRangeFromPoint(Point, PointOptions) method as the equivalent of GetCharIndexFromPosition. This method retrieves the degenerate (empty) text range at, or nearest to, a particular point on the screen. It returns a ITextRange object and the StartPosition property of ITextRange is similar to the character index returned by GetCharIndexFromPosition method.

    The following is a simple sample:

    XAML:

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <RichEditBox x:Name="editor" />
    </Grid>
    

    Code-behind:

    public MainPage()
    {
        this.InitializeComponent();
        editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, @"This is a text for testing.");
        editor.AddHandler(PointerMovedEvent, new PointerEventHandler(editor_PointerMoved), true);
    }
    
    private void editor_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        var position = e.GetCurrentPoint(editor).Position;
    
        var range = editor.Document.GetRangeFromPoint(position, Windows.UI.Text.PointOptions.ClientCoordinates);
    
        System.Diagnostics.Debug.WriteLine(range.StartPosition);
    }