none
How to SelectAll in TextBox when TextBox gets focus by mouse click?

    Question

  • If you click into the adress bar of the internet explorer, the adress will get selected. Only the second click sets the caret into the mouse position.

     

    I'd like to have this in my TextBox. I tried to override OnGotFocus and call SelectAll(), but this only works if the TextBox gets it focus by keyboard. If the TextBox is clicked by mouse, the text is selected for a split second, then it is deselected again and the caret is set.

     

    Thanks,
    Sam

    Thursday, September 27, 2007 1:43 PM

Answers

  • This should give you a TextBox with behaviors similar to the IE address bar:

     

    Code Block

     

    <TextBox

        MouseDoubleClick="SelectAddress"

        GotKeyboardFocus="SelectAddress"

        PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" />

     

     

    Here's the code behind:

     

    Code Block

     

    private void SelectAddress(object sender, RoutedEventArgs e)

    {

        TextBox tb = (sender as TextBox);

        if (tb != null)

        {

            tb.SelectAll();

        }

    }

     

    private void SelectivelyIgnoreMouseButton(object sender,

        MouseButtonEventArgs e)

    {

        TextBox tb = (sender as TextBox);

        if (tb != null)

        {

            if (!tb.IsKeyboardFocusWithin)

            {

                e.Handled = true;

                tb.Focus();

            }

        }

    }

     

     

    Thursday, September 27, 2007 4:49 PM

All replies

  • This should give you a TextBox with behaviors similar to the IE address bar:

     

    Code Block

     

    <TextBox

        MouseDoubleClick="SelectAddress"

        GotKeyboardFocus="SelectAddress"

        PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" />

     

     

    Here's the code behind:

     

    Code Block

     

    private void SelectAddress(object sender, RoutedEventArgs e)

    {

        TextBox tb = (sender as TextBox);

        if (tb != null)

        {

            tb.SelectAll();

        }

    }

     

    private void SelectivelyIgnoreMouseButton(object sender,

        MouseButtonEventArgs e)

    {

        TextBox tb = (sender as TextBox);

        if (tb != null)

        {

            if (!tb.IsKeyboardFocusWithin)

            {

                e.Handled = true;

                tb.Focus();

            }

        }

    }

     

     

    Thursday, September 27, 2007 4:49 PM
  • A little late on the thank you here, but THANK YOU!  Exactly what I was looking for.
    Friday, December 17, 2010 10:31 PM
  • Well done, man. Very helpful as I needed this.
    Thursday, August 25, 2011 7:10 PM