.netwpfsilverlighttextbox

How to automatically select all text on focus in WPF TextBox?


If I call SelectAll from a GotFocus event handler, it doesn't work with the mouse - the selection disappears as soon as mouse is released.

EDIT: People are liking Donnelle's answer, I'll try to explain why I did not like it as much as the accepted answer.


Solution

  • Don't know why it loses the selection in the GotFocus event.

    But one solution is to do the selection on the GotKeyboardFocus and the GotMouseCapture events. That way it will always work.

    -- Edit --

    Adding an example here to show people how to work around some the mentioned drawbacks:

    private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        // Fixes issue when clicking cut/copy/paste in context menu
        if (textBox.SelectionLength == 0) 
            textBox.SelectAll();
    }
    
    private void TextBox_LostMouseCapture(object sender, MouseEventArgs e)
    {
        // If user highlights some text, don't override it
        if (textBox.SelectionLength == 0) 
            textBox.SelectAll();
    
        // further clicks will not select all
        textBox.LostMouseCapture -= TextBox_LostMouseCapture; 
    }
    
    private void TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        // once we've left the TextBox, return the select all behavior
        textBox.LostMouseCapture += TextBox_LostMouseCapture;
    }