Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programatically set Focus to a TextBox in Windows Phone

In a Windows Phone app I have an TextBox and a Button. The user writes some text to the TextBox and taps the Button, the text from the TextBox is added to a list. The TextBox loses focus after the Button is tapped.

What I want to do is to set the focus back to the TextBox after the Button is tapped so the user can continue writing another text without needing to tap the TextBox.

I tried calling the Focus() method of the TextBox in the Button handler but this does not work. is there another, if any, way to do this?

like image 592
Igor Kulman Avatar asked Dec 12 '22 16:12

Igor Kulman


2 Answers

When Button clicked try to add bollean flag = true. Then check this flag on event OnTextBoxLostFocus.

<TextBox x:Name="tb" Grid.Row="1" LostFocus="Tb_OnLostFocus"/>
<Button x:Name="btn" Click="Btn_OnClick" />

 public partial class MainPage : PhoneApplicationPage
{
    private bool flag;
    public MainPage()
    {
        InitializeComponent();
    }

    private void Btn_OnClick(object sender, RoutedEventArgs e)
    {
        flag = true;
        tb.Focus();
    }

    private void Tb_OnLostFocus(object sender, RoutedEventArgs e)
    {
        if (!flag) return;
        tb.Focus();
        flag = false;
    }
}

Hope its help.

like image 154
jimpanzer Avatar answered Dec 14 '22 07:12

jimpanzer


I have tried a lot of solutions, but this is the only one that works for me (Windows Phone 8.1 app). First catch your TextBox's Loaded event, then call Focus(FocusState.Keyboard).

private void myTextBox_Loaded(object sender, RoutedEventArgs e)
{
    myTextBox.Focus(FocusState.Keyboard);
}
like image 34
lccmpn Avatar answered Dec 14 '22 06:12

lccmpn