简体   繁体   中英

Issue with setting the focus for textbox

I am working with UWP app using MVVM pattern, below is my code snippet to set the focus, but it not setting the focus to textbox.

XAML

<TextBox FontWeight="Bold" FontSize="32" Text="{Binding ProSeg1, Mode= TwoWay}" TextAlignment="Center" MaxLength="3" 
                             x:Name="txtSeg" KeyUp="txtSeg_KeyUp"
                             Style="{StaticResource textboxTemplate}" Width="105" />

UserControl.xaml.cs

//this code is executed from constructor.
bool val = txtSeg.Focus( FocusState.Keyboard);

Variable val is always returned false. In another instance, the same code has used for another TextBox , but it is triggered by a Button event and it works fine.

Calling Focus in constructor is too early, as the control is not yet ready to receive focus and will always return false . You must wait until the user control or at least the TextBox is fully loaded. In the constructor attach the Loaded event:

this.Loaded += UserControl_Loaded;

And add the following event handler:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    txtSeg.Focus(FocusState.Programmatic);
}

Also note that you should use FocusState.Programmatic as the Keyboard is reserved for when the control gets focus naturally using the Tab key whereas Programmatic is for setting focus in code.

You should check whether or not your XAML has been loaded. If you set the focus in the Window constructor the view won't be loaded so you will have to put your bool val = txtSeg.Focus( FocusState.Keyboard); in a Loaded event.

txtSeg won't be focusable until the window is loaded

You could attach to Window loaded or to Textbox Loaded to focus to your textbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM