Way to obtain the word cursor is on, in WPF RichTextBox Control

Viewed 3370

I would like to know how I can get the word that current cursor is on, in WPF RichTextBox. I am aware that RichTextBox has Selection Property. However, this only gives me the text that is highlighted in the RichTextBox. Instead I would like to know the word the cursor is on even if the whole word is not highlighted.

Any tips are appreciated.

5 Answers

Here is my alternative solution using LINQ and Dependency Property:

public class SelectionRichTextBox : RichTextBox
{
    public SelectionRichTextBox()
    {
        // Use base class style
        SetResourceReference(StyleProperty, typeof(RichTextBox));
    }

    public static readonly DependencyProperty SelectedWordProperty =
        DependencyProperty.Register(
                "SelectedWord",
                typeof(string),
                typeof(SelectionRichTextBox),
                new PropertyMetadata("")
                );

    public string SelectedWord
    {
        get
        {
            return (string)GetValue(SelectedWordProperty);
        }
        set
        {
            SetValue(SelectedWordProperty, value);
        }
    }

    protected override void OnMouseUp(MouseButtonEventArgs e)
    {
        TextPointer cursorPosition = CaretPosition;

        string strBeforeCursor = cursorPosition.GetTextInRun(LogicalDirection.Backward);
        string strAfterCursor = cursorPosition.GetTextInRun(LogicalDirection.Forward);

        string wordBeforeCursor = strBeforeCursor.Split().Last();
        string wordAfterCursor = strAfterCursor.Split().First();

        string text = wordBeforeCursor + wordAfterCursor;

        SelectedWord = string.Join("", text
            .Where(c => char.IsLetter(c))
            .ToArray());

        base.OnMouseUp(e);
    }
}

After that, you can use it in binding like this:

    <custom:SelectionRichTextBox
            SelectedWord="{Binding SelectedWord, Mode=OneWayToSource}"/>
Related