Reputation: 31
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.
Upvotes: 1
Views: 1672
Reputation: 784
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
Upvotes: 0
Reputation: 39072
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.
Upvotes: 4