How to select all text in textbox when it gets focus

You can try this code,

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        String sSelectedText = mytextbox.SelectedText;
    }

If user clicks on copy icon that comes after selection it will get copied, if you want to do it programmatically you can try this

DataPackage d = new DataPackage();
d.SetText(selectedText);
Clipboard.SetContent(d);

I would suggest doing the copying in some other event rather than gotfocus, as this will be triggered immediately after user taps on text field so this method will be called when there is no text actually entered.


I had this same problem on WPF and managed to solve it. Not sure if you can use what I used but essentially your code would look like:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox .CaptureMouse()
    }

    private void TextBox_GotMouseCapture(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox.SelectAll();
    }

private void TextBox_IsMouseCaptureWithinChanged(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox.SelectAll();
    }

All events hooked up to the original textbox. If this doesn't work for you, maybe you can replace CaptureMouse with CaptureTouch (and use the appropriate events). Good luck!