以编程方式将焦点设置为 Windows Phone 中的文本框

问题描述:

在 Windows Phone 应用程序中,我有一个 TextBox 和一个 Button.用户向 TextBox 写入一些文本并点击 Button,来自 TextBox 的文本被添加到列表中.点击 Button 后,TextBox 失去焦点.

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.

我尝试在 Button 处理程序中调用 TextBox 的 Focus() 方法,但这不起作用.如果有的话,还有其他方法吗?

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?

当 Button 单击时尝试添加 bollean flag = true.然后在事件 OnTextBoxLostFocus 上检查此标志.

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;
    }
}

希望对您有所帮助.