Click here to Skip to main content
15,886,100 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can I make password Box to take normal text without masking it, if yes how to do it in wpf. I have a password box which should display "Password" Text prior to entering password. And on entering password the it will be displayed as a masked text. Please help.

Thanks in advance
Posted
Updated 14-May-19 7:24am
v2

Write a custom PasswordBox of your own specification. Writing custom control in WPF is very easy and simple.

Examples:

Create a WPF Custom Control, Part 1[^]

Create a WPF Custom Control, Part 2[^]

Note: These are examples how to write a custom control in WPF.

or try the below style, Set the HintTextBoxStyle to the PasswordBox and give your message in Tag.

XML
<Style x:Key="HintLabel" TargetType="{x:Type TextBlock}">
        <Setter Property="IsHitTestVisible" Value="False" />
        <Setter Property="FontStyle" Value="Italic" />
        <Setter Property="FontSize" Value="11" />
        <Setter Property="Margin" Value="2,2,0,0" />
        <Setter Property="Visibility" Value="Hidden" />
        <Setter Property="Foreground" Value="Gray" />
        <Setter Property="FontFamily" Value="Aial" />
    </Style>

    <SolidColorBrush x:Key="ListBorder" Color="#FF7F9DB9"/>

    <Style x:Key="HintTextBoxStyle"
                   TargetType="{x:Type TextBox}">
            <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
            <Setter Property="BorderBrush" Value="{StaticResource ListBorder}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="Padding" Value="2"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid Width="Auto" Height="Auto">
                        <Border x:Name="Bd" SnapsToDevicePixels="true" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3,3,3,3" BorderBrush="#FF757575" Margin="0,0,0,0"
                                Background="{TemplateBinding Background}">                            
                            <Grid>
                                <ScrollViewer x:Name="PART_ContentHost" Margin="0,0,0,0"
                                                  SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                                <TextBlock x:Name="PART_SearchHintLabel"
                                           Style="{StaticResource HintLabel}"
                                           Text="{TemplateBinding Tag}"
                                           Visibility="Collapsed" />
                            </Grid>
                        </Border>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsFocused" Value="True">
                            <Setter Property="BorderBrush" TargetName="Bd" Value="#FF7AA639"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="BorderBrush" TargetName="Bd" Value="#FF7AA639"/>
                        </Trigger>
                        <Trigger Property="UIElement.IsEnabled">
                            <Setter Property="Panel.Background" TargetName="Bd">
                                <Setter.Value>
                                    <DynamicResource ResourceKey="{x:Static SystemColors.ControlBrushKey}" />
                                </Setter.Value>
                            </Setter>
                            <Setter Property="TextElement.Foreground">
                                <Setter.Value>
                                    <DynamicResource ResourceKey="{x:Static SystemColors.GrayTextBrushKey}" />
                                </Setter.Value>
                            </Setter>
                            <Trigger.Value>
                                <s:Boolean>False</s:Boolean>
                            </Trigger.Value>
                        </Trigger>                        
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsFocused" Value="False" />
                                <Condition Property="Text" Value="" />
                            </MultiTrigger.Conditions>
                            <Setter TargetName="PART_SearchHintLabel"
                                            Property="Visibility"
                                            Value="Visible" />
                        </MultiTrigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsFocused" Value="False" />
                                <Condition Property="Text" Value="{x:Null}" />
                            </MultiTrigger.Conditions>
                            <Setter TargetName="PART_SearchHintLabel"
                                            Property="Visibility"
                                            Value="Visible" />
                        </MultiTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>



Mark it as Answer, if it is helpful
 
Share this answer
 
v3
Comments
Member 7725461 4-Mar-11 7:17am    
Can you please give me an example for the same
Venkatesh Mookkan 4-Mar-11 7:29am    
Updated the answer
Venkatesh Mookkan 4-Mar-11 7:34am    
Updated the answer again
Sandeep Mewara 4-Mar-11 8:22am    
Good answer and follow up. 5!
Hi,

look here at the WPF Watermark PasswordBox:
http://stackoverflow.com/questions/1607066/wpf-watermark-passwordbox-from-watermark-textbox[^]

Hope this is what you are looking for
 
Share this answer
 
1. Create UserControl with 2 controls: Textbox and passwordcontrol. One is visible, the other is hidden.
2. Create checkbox to alternate their visibility.

UserControl's xaml:

XML
<usercontrol x:class="ITWPFControls.WpfPasswordControl" xmlns:x="#unknown">
                         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                         mc:Ignorable="d"
                         d:DesignHeight="35" d:DesignWidth="450"&gt;
    <grid horizontalalignment="Stretch" margin="3" name="stackPanel1" verticalalignment="Stretch" width="Auto" height="Auto">
        <grid.columndefinitions>
            <columndefinition width="100*" />
            <columndefinition width="Auto" />
        </grid.columndefinitions>
        <textbox height="Auto" name="TB1" verticalcontentalignment="Center" margin="2" padding="2" grid.column="0" />
        <passwordbox height="Auto" name="PWB1" verticalcontentalignment="Center" margin="2" padding="2" grid.column="0" visibility="Hidden" />
        <checkbox content="Masked" margin="3" name="CB1" height="Auto" width="Auto" horizontalalignment="Center" horizontalcontentalignment="Center" grid.columnspan="1" verticalcontentalignment="Top" grid.column="1" padding="3,0,3,3" verticalalignment="Center" click="CB1_Click" />
    </grid>
</usercontrol>




3. create UserControl's property "Password". Password gets its value from actually visible control

C#
public string Password
{
    get
    {
        if (TB1.Visibility == System.Windows.Visibility.Visible) {
            return TB1.Text;
        } else if (PWB1.Visibility == System.Windows.Visibility.Visible) {
            return PWB1.Password;
        }
        return "";
    }
}



4. implement in UserControl's cs alternating the visiblility:

4.1. the new visible takes its value from old visible
4.2. the new visible gets its carret and focus

C#
private void CB1_Click(object sender, RoutedEventArgs e)
{
    string _Password = Password;
    TB1.Visibility = CB1.IsChecked == true ? System.Windows.Visibility.Hidden : System.Windows.Visibility.Visible;
    PWB1.Visibility = CB1.IsChecked == true ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
    int _Selection = _Password.Length;
    if (_Selection > 0) {
        if (TB1.Visibility == System.Windows.Visibility.Visible) {
            TB1.Text = _Password;
            TB1.SelectionStart = _Selection;
            TB1.Focus();
        } else if (PWB1.Visibility == System.Windows.Visibility.Visible) {
            PWB1.Password = _Password;
            MethodInfo _MI = PWB1.GetType().GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic);
            if (_MI != null) {
                _MI.Invoke(PWB1, new object[] { _Selection, 0 });
            }
            PWB1.Focus();
        }
    }
}
 
Share this answer
 
v6
It's very simple to do that.
First you should to add the value `PasswordChar` in your PasswordBox:
XML
<PasswordBox Name="PasswordHidden" PasswordChar="*"/>

Next under the PasswordBox tag you should to add a TextBox with `Visibility` value setted to Hidden:
XML
<TextBox Name="PasswordUnmask" Visibility="Hidden"/>

And a trigger to show / hide the password, for example a simple text or a button. In my case I'm using a simple text.
XML
<TextBlock Name="ShowPassword"/>

Next you need to add 3 different events in the trigger element, for example (this is valid for TextBlock or Image, if you want to use a Button you should to choose another events):
XML
<TextBlock x:Name="ShowPassword" Text="SHOW" PreviewMouseDown="ShowPassword_PreviewMouseDown" PreviewMouseUp="ShowPassword_PreviewMouseUp" MouseLeave="ShowPassword_MouseLeave"/>

The events are `PreviewMouseDown` `PreviewMouseUp` and `MouseLeave` but you can choose the appropriate event for your situation.
Now in your code you need to program the functions:
C#
private void ShowPassword_PreviewMouseDown(object sender, MouseButtonEventArgs e) => ShowPasswordFunction();
private void ShowPassword_PreviewMouseUp(object sender, MouseButtonEventArgs e) => HidePasswordFunction();
private void ShowPassword_MouseLeave(object sender, MouseEventArgs e) => HidePasswordFunction();

private void ShowPasswordFunction()
{
    ShowPassword.Text = "HIDE";
    PasswordUnmask.Visibility = Visibility.Visible;
    PasswordHidden.Visibility = Visibility.Hidden;
    PasswordUnmask.Text = PasswordHidden.Password;
}
 
private void HidePasswordFunction()
{
    ShowPassword.Text = "SHOW";
    PasswordUnmask.Visibility = Visibility.Hidden;
    PasswordHidden.Visibility = Visibility.Visible;
}
 
Share this answer
 
v2
Comments
CHill60 15-May-19 5:12am    
This shows/unshows the password. That is not what the OP asked for.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900