hap497
hap497

Reputation: 162965

How to select all text in textbox when it gets focus

In Windows phone, how can I select all text in Textbox when the TextBox has focus?

I try setting the get focus property of Textbox:

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

        textBox .SelectAll();
    }

What I see is I see all the text is being selected for 1-2 sec and then it goes back to cursor mode (i.e. 1 blink line).

Upvotes: 10

Views: 35967

Answers (3)

Waruna Manjula
Waruna Manjula

Reputation: 3477

protected override void OnStartup(StartupEventArgs e)
{
    //works for tab into textbox
    EventManager.RegisterClassHandler(typeof(TextBox),
        TextBox.GotFocusEvent,
        new RoutedEventHandler(TextBox_GotFocus));
    //works for click textbox
    EventManager.RegisterClassHandler(typeof(Window),
        Window.GotMouseCaptureEvent,
        new RoutedEventHandler(Window_MouseCapture));

    base.OnStartup(e);
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    (sender as TextBox).SelectAll();
}

private void Window_MouseCapture(object sender, RoutedEventArgs e)
{
    var textBox = e.OriginalSource as TextBox;
    if (textBox != null)
         textBox.SelectAll(); 
}

Upvotes: 0

Tyress
Tyress

Reputation: 3653

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!

Upvotes: 7

Prasanna Aarthi
Prasanna Aarthi

Reputation: 3453

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.

Upvotes: 1

Related Questions