Home Ask Login Register

Developers Planet

Your answer is one click away!

taxer03 February 2016

WPF textbox/password box text disappear on click

I'm making a login screen for a wpf application. I want 2 textboxes, one for username and password.

For username, I have used a textbox and added text to it ('Username') which disappears when the user clicks on it to enter their username. I done it with the code below.

I can't seem to replicate this for password. I don't believe i'll be able to use a textbox as I wont be able to disguise the user input to *'s or whatever, and I cant figure out a way to hardcode 'password' into the box for it to disappear when the user clicks.

How can I do this? I know its possible as loads of sites have this functionality but I cant figure it out after googling for a long time!

I should stress that im completely new to programming so answers aimed at a complete novice would be much appreciated!


xaml: GotFocus="UserNameTextbox_OnGotFocus" Foreground="#FFA19DA1"/>

private void UserNameTextbox_OnGotFocus(object sender, RoutedEventArgs e)
        UserNameTextbox.Text = "";

Username example here


Василий Шапенко February 2016

Looks like you need to customize your password box a little bit. One way to achieve it is to create UserControl with a password box and textblock over it. On GotFocus for password box you just set visibility of textblock to Collapsed. And dont forger to set HitTestVisible=false for textblock.

Kelly Barnard February 2016

Try this technique:


<Window x:Class="WpfApplication16.MainWindow"
        Title="MainWindow" Height="100" Width="342.111" Background="DarkBlue">
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        <TextBlock Text="User Name:" HorizontalAlignment="Right" Foreground="White" />
        <TextBox Name="txtUserName" Grid.Column="1" TextChanged="txtUserName_TextChanged" />
        <TextBlock Name="tbUsername" Text="User Name" Foreground="Gray" IsHitTestVisible="False" Margin="4,0" VerticalAlignment="Center" Grid.Column="1" />    

        <TextBlock  Grid.Row="1" Text="Password:" Foreground="White" HorizontalAlignment="Right" />       
        <PasswordBox Name="pwbPassword" Grid.Row="1" Grid.Column="1" PasswordChanged="pwbPassword_PasswordChanged" />
        <TextBlock Name="tbPassword" Grid.Row="1" Grid.Column="1" Foreground="Gray" Margin="4,0" VerticalAlignment="Center" Text="Password" IsHitTestVisible="False" />

Code Behind:

public partial class MainWindow : Window
    public MainWindow()

    private void txtUserName_TextChanged(object sender, TextChangedEventAr 

Post Status

Asked in February 2016
Viewed 3,777 times
Voted 12
Answered 2 times


Leave an answer

Quote of the day: live life