Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on PasswordBox when application starts

Tags:

c#

wpf

Is there a reason why I can't set the focus on my PasswordBox Control?

C#:

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

XAML:

<PasswordBox x:Name="_password" Width="200" Height="30" FontSize="14" 
 KeyDown="_password_KeyDown"/>
like image 831
arti Avatar asked Apr 28 '17 09:04

arti


3 Answers

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}"
         ... />
like image 145
ajb101 Avatar answered Nov 17 '22 13:11

ajb101


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>

enter image description here

like image 32
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 17 '22 11:11

ΦXocę 웃 Пepeúpa ツ


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.

like image 40
Jurjen Avatar answered Nov 17 '22 12:11

Jurjen