Is there a reason why I can't set the focus on my PasswordBox Control?
public Login()
{
InitializeComponent();
_password.Focus();
}
<PasswordBox x:Name="_password" Width="200" Height="30" FontSize="14"
KeyDown="_password_KeyDown"/>
You're doing it too early when you're setting it in the constructor. Try the Load event handler instead.
public Login()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Login_Loaded);
}
void Login_Loaded(object sender, RoutedEventArgs e)
{
_password.Focus();
}
You can also do it in XAML:
<Window ....
FocusManager.FocusedElement="{Binding ElementName=_password}"
... />
WPF offers a nice 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>
If you want to do it in XAML
:
<StackPanel FocusManager.FocusedElement="{Binding ElementName=_password}">
<PasswordBox Name="_password" />
</StackPanel>
Please note (MSDN):
There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With