Set focus on PasswordBox when application starts

Is there a reason why I can’t adjust the focus on my PasswordBox Control?

WITH#:

public Login() { InitializeComponent(); _password.Focus(); } 

XAML:

 <PasswordBox x:Name="_password" Width="200" Height="30" FontSize="14" KeyDown="_password_KeyDown"/> 
+5
source share
3 answers

You do this too early when you install it in the constructor. Instead, try a load event handler.

 public Login() { InitializeComponent(); this.Loaded += new RoutedEventHandler(Login_Loaded); } void Login_Loaded(object sender, RoutedEventArgs e) { _password.Focus(); } 

You can also do this in XAML:

  <Window .... FocusManager.FocusedElement="{Binding ElementName=_password}" ... /> 
+3
source

WPF offers a great elegant way (xaml only)

 FocusManager.FocusedElement="{Binding ElementName=pass}"> 

Example:

 <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525" FocusManager.FocusedElement="{Binding ElementName=pass}"> <Grid> <Button Content="Button" HorizontalAlignment="Left" Margin="261,165,0,0" VerticalAlignment="Top" Width="75"/> <TextBox x:Name="name" HorizontalAlignment="Left" Height="23" Margin="70,193,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/> <TextBox x:Name="pass" HorizontalAlignment="Left" Height="23" Margin="70,165,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/> </Grid> </Window> 

enter image description here

+2
source

If you want to do this in XAML :

 <StackPanel FocusManager.FocusedElement="{Binding ElementName=_password}"> <PasswordBox Name="_password" /> </StackPanel> 

Please note ( MSDN ):

On the desktop, there can only be one item with a keyboard focus. In WPF, an element that has keyboard focus will have IsKeyboardFocused set to true.

+1
source

Source: https://habr.com/ru/post/1267268/


All Articles