Double click selecting words separated by periods like "i.a."

Viewed 69

My goal is to double click the entire part of "i.a." like this however the default for WPF is it selects each part of the string individually

Sample:

<TextBox>Reason for contact: i.a.</TextBox>

What I've found so far

I've attempted to use SpellCheck.CustomDictionaries, word selection is unaffected by these.

1 Answers

Try this one. It selects text part depending on caret position (which is SelectionStart - 1) from nearest left whitespace ' ' (or start of string) to nearest right one (or end of string).

private void OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    if (sender is TextBox tb)
    {
        char[] chars = tb.Text.ToCharArray();

        int i;
        // Find nearest left whitespace or start of string
        for (i = tb.SelectionStart - 1; i >= 0 && chars[i] != ' '; i--);
        int selectionStart = i + 1;

        // Find nearest right whitespace or end of string
        for (i = tb.SelectionStart; i < chars.Length && chars[i] != ' '; i++);
        int selectionLength = i - selectionStart;
        
        tb.Select(selectionStart, selectionLength);
    }
}

enter image description here

Related