Skip to main content

Microsoft Silverlight

Answered Question PasswordBox ControlRSS Feed

(1)

pbrooks
pbrooks

Contributor

Contributor

2671 points

355 Posts

Silverlight MVP

PasswordBox Control

Are there any plans to add a PasswordBox control to Silverlight 2?  Thanks!

If this has answered your question, please click on "Mark as Answer" on this post.

Thanks,
Page Brooks
Silverlight MVP, MCSD
PageBrooks.com | @pbrooks

kirtid
kirtid

Member

Member

28 points

10 Posts

Microsoft

Re: PasswordBox Control

PasswordBox is crucial and we are investigating the possibility of supporting it but have no concrete plans yet.

Kirti Deshpande
Program Manager, Silverlight and ASP.NET AJAX
Microsoft

This posting is provided "AS IS" with no warranties, and confers no rights.

mhaggag
mhaggag

Member

Member

308 points

59 Posts

Re: PasswordBox Control

It's possible to implement a PasswordBox on top of the built-in TextBox. It involves a little bit of plumbing, though. You'll have to hook yourself into the keydown and TextChanged events on the textbox, and replace any entered characters on the fly with the password character. The tricky part is handling selection and deletion.

I've already written such a control internally. I'll see if I can release it publicly next week.

Muhammad Haggag.
SDE, Silverlight (Text feature team)

BeSilver
BeSilver

Member

Member

76 points

38 Posts

Re: PasswordBox Control

Would be great if you could release the code!

------------------------
blogging @ www.24100.net

crpietschmann
crpietsc...

Member

Member

217 points

57 Posts

Re: PasswordBox Control

Here's a simple PasswordTextBox control that I wrote to use for now; until they update the TextBox in Silverlight to have this feature.

http://pietschsoft.com/post/2008/03/PasswordTextBox-for-Silverlight-2-Beta-1.aspx

Also, I've posted the code below for convenience:

/// Copyright 2008 Chris Pietschmann (http://pietschsoft.com)
/// This work is licensed under a Creative Commons Attribution 3.0 United States License
/// http://creativecommons.org/licenses/by/3.0/us/
///
/// This is a Password TextBox built for use with Silverlight 2 Beta 1
/// The reason this was built, is because the standard TextBox in
/// Silverlight 2 Beta 1 does not have Password support.
///

using System.Windows.Controls;

namespace SilverlightPasswordTextBox
{
    public partial class PasswordTextBox : TextBox
    {
        public PasswordTextBox()
        {
            this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
            this.KeyDown += new System.Windows.Input.KeyEventHandler(PasswordTextBox_KeyDown);
        }

        public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // Take the new character(s) at the front of the string
            // and store them with what's already being stored
            int newCharLength = base.Text.Length - _Text.Length;
            if (newCharLength > 0)
                _Text += base.Text.Substring(0, newCharLength);

            DisplayMaskedCharacters();
        }

        public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            // If Backspace or Delete are pressed, then clear the TextBox
            if (e.Key == System.Windows.Input.Key.Back
                || e.Key == System.Windows.Input.Key.Delete)
            {
                _Text = "";
                base.Text = "";
            }
        }

        private string _Text = "";
        public new string Text
        {
            get { return _Text; }
            set
            {
                _Text = value;
                DisplayMaskedCharacters();
            }
        }

        private void DisplayMaskedCharacters()
        {
            // This changes the Text property of the base TextBox
            // class to display all Asterisks in the control
            string p = "";
            for (int i = 0; i < _Text.Length; i++)
                p += "*";
            base.Text = p;
        }
    }
}

 

Microsoft MVP - Windows Live Platform
Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: PasswordBox Control

crpietschmann,

Your passwordbox code works great. Found one problem is that as you typing the cursor is always at the beginning. So the text you put in is backward. The fix is to add one Select line in the DisplayMaskedCharacter function:

private void DisplayMaskedCharacters()

{

// This changes the Text property of the base TextBox

// class to display all Asterisks in the control

string p = "";

for (int i = 0; i < _Text.Length; i++)

p += "*";base.Text = p;

Select(_Text.Length, 0);

}

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

Basti0203
Basti0203

Member

Member

30 points

14 Posts

Re: PasswordBox Control

Hi,

 i had some problems using your code. If you typed in the second charcter you selected the first one to add which is already an asterix.
You also never cleaned the textbox if the user selected everything and typed in a new character. I also inherited from WatermarkedTextbox.

Here is my changed code:

public partial class PasswordTextBox : WatermarkedTextBox

{

public PasswordTextBox()

{

this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);this.KeyDown += new System.Windows.Input.KeyEventHandler(PasswordTextBox_KeyDown);

}

public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)

{

// Take the new character(s) at the front of the string

// and store them with what's already being stored

int newCharLength = base.Text.Length - _Text.Length;if (newCharLength > 0)

{

// Change: Only select the new characters

_Text +=
base.Text.Substring(base.Text.Length - newCharLength, newCharLength);

}

else if (newCharLength < 0)

{

// Change: You have to clear the textbox. Otherwise you cannot select the complete text and type in something new

_Text =
"";

}

 

DisplayMaskedCharacters();

}

public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)

{

// If Backspace or Delete are pressed, then clear the TextBox

if (e.Key == System.Windows.Input.Key.Back|| e.Key == System.Windows.Input.Key.Delete)

{

_Text = "";

base.Text = "";

}

}

private string _Text = "";public new string Text

{

get { return _Text; }

set

{

_Text =
value;

DisplayMaskedCharacters();

}

}

private void DisplayMaskedCharacters()

{

// This changes the Text property of the base TextBox

// class to display all Asterisks in the control

string p = "";

for (int i = 0; i < _Text.Length; i++)

p += "*";base.Text = p;

Select(_Text.Length, 0);

}

}

mchlSync
mchlSync

Star

Star

14606 points

2,730 Posts

Silverlight MVP

Re: PasswordBox Control

What if the user types "Delete"  or "Backspace" or arrow keys? I think it's good if we have it too. at least, "backspace" should be supported.

(If this has answered your question, please click on "Mark as Answer" on this post. Thank you!)

Regards,
Michael Sync
Silverlight MVP

Blog : http://michaelsync.net


Angelo.Ciffa
Angelo.C...

Member

Member

2 points

1 Posts

Re: PasswordBox Control

Hello,

I had to do this, and here is a solution  Smile

 

 void LoginTBPassword_KeyDown(object sender, KeyEventArgs e)
        {
            // Here we test the key that has been pressed

            if (e.Key == System.Windows.Input.Key.Back)
            {
                DeleteAt(LoginTBPassword.SelectionStart);
            }
            else if (e.Key == System.Windows.Input.Key.Delete)
            {
                DeleteAt(LoginTBPassword.SelectionStart);
            }
        }

 

  private void DeleteAt(int position)
    {
            try //this try catch could be replaced by a test that would check if we are not out of range
            {
                pText = pText.Remove(position , 1);
                LoginTBPassword.Text = LoginTBPassword.Text.Remove(position , 1);
            }
            catch (Exception e)
            {
            }
     }

 

                                      Angelo C.
 

crpietschmann
crpietsc...

Member

Member

217 points

57 Posts

Answered Question

Re: PasswordBox Control

Thanks, for all the suggestions people! I didn't know there would be so much interest; I also had a couple people contact me through my blog regarding this code.

Here's an updated version that includes better support for the Backspace and Delete keys, and maintains the caret/cursor position.

/// Copyright 2008 Chris Pietschmann (http://pietschsoft.com)
/// This work is licensed under a Creative Commons Attribution 3.0 United States License
/// http://creativecommons.org/licenses/by/3.0/us/
///
/// This is a Password TextBox built for use with Silverlight 2 Beta 1
/// The reason this was built, is because the standard TextBox in
/// Silverlight 2 Beta 1 does not have Password support.
/// Original Link: http://pietschsoft.com/post/2008/03/PasswordTextBox-for-Silverlight-2-Beta-1.aspx
///

using System.Windows.Controls;

namespace SilverlightPasswordTextBox
{
    public partial class PasswordTextBox : TextBox
    {
        public PasswordTextBox()
        {
            this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
            this.KeyDown += new System.Windows.Input.KeyEventHandler(PasswordTextBox_KeyDown);
        }

        #region Event Handlers

        public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (base.Text.Length >= _Text.Length)
                _Text += base.Text.Substring(_Text.Length);
            DisplayMaskedCharacters();
        }

        public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            int cursorPosition = this.SelectionStart;
            int selectionLength = this.SelectionLength;

            // Handle Delete and Backspace Keys Appropriately
            if (e.Key == System.Windows.Input.Key.Back
                || e.Key == System.Windows.Input.Key.Delete)
            {
                if (cursorPosition < _Text.Length)
                    _Text = _Text.Remove(cursorPosition, (selectionLength > 0 ? selectionLength : 1));
            }
           
            base.Text = _Text;
            this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
            DisplayMaskedCharacters();
        }

        #endregion

        #region Private Methods

        private void DisplayMaskedCharacters()
        {
            int cursorPosition = this.SelectionStart;
           
            // This changes the Text property of the base TextBox class to display all Asterisks in the control
            base.Text = new string(_PasswordChar, _Text.Length);

            this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
        }

        #endregion

        #region Properties

        private string _Text = string.Empty;
        /// <summary>
        /// The text associated with the control.
        /// </summary>
        public new string Text
        {
            get { return _Text; }
            set
            {
                _Text = value;
                DisplayMaskedCharacters();
            }
        }

        private char _PasswordChar = '*';
        /// <summary>
        /// Indicates the character to display for password input.
        /// </summary>
        public char PasswordChar
        {
            get { return _PasswordChar; }
            set { _PasswordChar = value; }
        }

        #endregion
    }
}

Microsoft MVP - Windows Live Platform
Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control

ferdna
ferdna

Member

Member

108 points

49 Posts

Re: PasswordBox Control

bump. sorry I had to bump it, since this is V V I (Very Valuable Information) here.



============================================================
It Is Not That I'm Different! ... I'm Only Making The Difference!

crpietschmann
crpietsc...

Member

Member

217 points

57 Posts

Re: PasswordBox Control

[bump]...

Microsoft MVP - Windows Live Platform
Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control

HiHoSilver
HiHoSilver

Member

Member

16 points

12 Posts

Re: PasswordBox Control

Chris, could you show how this is done in VB? Thanks, Jim

crpietschmann
crpietsc...

Member

Member

217 points

57 Posts

Re: PasswordBox Control

Oh sure, no problem. Here you go.

'' Copyright 2008 Chris Pietschmann (http://pietschsoft.com)
'' This work is licensed under a Creative Commons Attribution 3.0 United States License
'' http://creativecommons.org/licenses/by/3.0/us/
''
'' This is a Password TextBox built for use with Silverlight 2 Beta 1
'' The reason this was built, is because the standard TextBox in
'' Silverlight 2 Beta 1 does not have Password support.
'' Original Link: http://pietschsoft.com/post/2008/03/PasswordTextBox-for-Silverlight-2-Beta-1.aspx
Public Class PasswordTextBox
    Inherits TextBox

    Public Sub PasswordTextBox_TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs) Handles Me.TextChanged
        If MyBase.Text.Length >= _Text.Length Then
            _Text += MyBase.Text.Substring(_Text.Length)
        End If
        DisplayMaskedCharacters()
    End Sub

    Public Sub PasswordTextBox_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles Me.KeyDown
        Dim cursorPosition As Integer = Me.SelectionStart
        Dim selectionLength As Integer = Me.SelectionLength

        '' Handle Delete and Backspace Keys Appropriately
        If e.Key = Key.Back Or e.Key = Key.Delete Then
            If cursorPosition < _Text.Length Then
                Dim lengthToRemove As Integer = 1
                If selectionLength > 0 Then lengthToRemove = selectionLength
                _Text = _Text.Remove(cursorPosition, lengthToRemove)
            End If
        End If

        MyBase.Text = _Text
        If cursorPosition > _Text.Length Then
            Me.Select(_Text.Length, 0)
        Else
            Me.Select(cursorPosition, 0)
        End If
        DisplayMaskedCharacters()
    End Sub

    Private Sub DisplayMaskedCharacters()
        Dim cursorPosition As Integer = Me.SelectionStart

        '' This changes the Text property of the base TextBox class to display all Asterisks in the control
        MyBase.Text = New String(_PasswordChar, _Text.Length)

        If cursorPosition > _Text.Length Then
            Me.Select(_Text.Length, 0)
        Else
            Me.Select(cursorPosition, 0)
        End If
    End Sub

    Private _Text As String = String.Empty
    Overloads Property Text() As String
        Get
            Return _Text
        End Get
        Set(ByVal value As String)
            _Text = value
            DisplayMaskedCharacters()
        End Set
    End Property

    Private _PasswordChar As Char = "*"
    Public Property PasswordChar() As Char
        Get
            Return _PasswordChar
        End Get
        Set(ByVal value As Char)
            _PasswordChar = value
        End Set
    End Property

End Class

 

Microsoft MVP - Windows Live Platform
Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control

HiHoSilver
HiHoSilver

Member

Member

16 points

12 Posts

Re: PasswordBox Control

Chris,

How do you wire this up? My app.xaml is loading page.xmal.   page.xmal has the textbox. page.xmal.vb  inherits 'UserControl', not 'TextBox'. If I create a seperate class with this code in it, how do I get the page.xmal to talk to the PasswordText.xmal when the inheritance is different? Can I place this logic directly into page.xmal? I tried this though, but then the class will only inherit either 'UserControl' or 'Textbox', but not both.

Can you help with this?

Thanks,
Jim

desopedr
desopedr

Member

Member

96 points

34 Posts

Re: PasswordBox Control

Hi,

Thx for this control. I've one question about dependency properties. I want to encode the Text with MD5 algo and I can do a method which does it but I prefer "override" the Text dependency property of TextBox control (changing the Setter to return the encoded string).
 

Is it possible to redefine an existing Dependency Property ? And how ?

 

Chris,

 Add new item to your projet (class.cs), delete the code and copy paste the passwordtextbox code. You can call it on the page.xaml adding a reference to the namespace of your passwordtextbox class

<UserControl x:Class="YourNamespace.HomePage" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:YourNamespace;assembly=YourAssembly">
  <Grid x:Name="LayoutRoot">
   
      <local:PasswordTextBox x:Name="PasswordTb" Grid.Row="0" Height="25" Width="100" />
   
  </Grid>
</UserControl>

Jhorra
Jhorra

Member

Member

522 points

475 Posts

Re: Re: PasswordBox Control

I'm trying to use this, but seem to have done something wrong.

This is the updated UserControl at the top of my page.xaml

<UserControl x:Class="UVNTV.Page"

xmlns="http://schemas.microsoft.com/client/2007"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="clr-namespace:UVNTV;assembly=PasswordTextBox"

Width="710" Height="480" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">

Here is the class I created

namespace UVNTV

{

public partial class PasswordTextBox : TextBox

{

}

}

doolittle
doolittle

Member

Member

74 points

26 Posts

PasswordBox Control

Hello

Great stuff, but I have a rather odd problem for which I don't see the solution.

I have a business object that contains a password property.  And I've bound this property (twoway) to a PasswordBox control.

But as value I of course get a string of 'password-char', as the dependency property 'Text' is changed...

Do you see a simple solution to fix this???  Or maybe I'm doing something wrong?

 
Thx a lot!!


 

crpietschmann
crpietsc...

Member

Member

217 points

57 Posts

Re: PasswordBox Control

doolittle:

Hello

Great stuff, but I have a rather odd problem for which I don't see the solution.

I have a business object that contains a password property.  And I've bound this property (twoway) to a PasswordBox control.

But as value I of course get a string of 'password-char', as the dependency property 'Text' is changed...

Do you see a simple solution to fix this???  Or maybe I'm doing something wrong?

Thx a lot!!

Could you re-explain the problem you are having? I'm not understanding what the problem is you are having, from your explanation above.

Thanks

Microsoft MVP - Windows Live Platform
Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control

doolittle
doolittle

Member

Member

74 points

26 Posts

Re: Re: PasswordBox Control

Ah sorry, that I wasn't clear in the description of my problem.

I'm using an 'Employee' object and that object has a property 'Password'.

In my UI I've bound this property to the 'Text' property of the Passwordbox control.  But the content of my Employee.Password then becomes for instance '***' when you've typed three characters for the password.  Instead of the actual value...

codereaver
codereaver

Member

Member

2 points

1 Posts

Re: PasswordBox Control

 This was great help also I inherited from watermarkedTextBox instead of Textbox to get the watermarked text in the box. and this is working great thanks.

crpietschmann
crpietsc...

Member

Member

217 points

57 Posts

Re: PasswordBox Control

I see the TextBox control in Silverlight 2 Beta 2 still doesn't support Passwords. I really hope this makes it into the RTM. Anyway, at least we can still use the code posted above. I haven't tried it in SL2B2 yet, but I'll test it out when I get a chance to see if any changes are needed.

Microsoft MVP - Windows Live Platform
Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control

crpietschmann
crpietsc...

Member

Member

217 points

57 Posts

Re: PasswordBox Control

I just tested my PasswordTextBox code in Silverlight 2 Beta 2, and it works just the same as it did in Beta 1.

Make sure you copy the code from the following link instead of the forum post above, so you get the latest code. Also, I have both C# and VB.NET versions of it listed at the link below.

http://pietschsoft.com/post/2008/03/PasswordTextBox-for-Silverlight-2-Beta-1.aspx

Microsoft MVP - Windows Live Platform
Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control

mhaggag
mhaggag

Member

Member

308 points

59 Posts

Re: PasswordBox Control

There will be a PasswordBox control in RTM, similar to that of WPF.

Muhammad Haggag.
SDE, Silverlight (Text feature team)

tomhat
tomhat

Member

Member

22 points

13 Posts

Re: PasswordBox Control

Note that Silverlight 2 Beta 2 removed the WatermarkedTextbox. If you try to use the WatermarkedTextbox by inheriting to it you will get a compiler error from the ValidateXaml task.

josh100
josh100

Member

Member

50 points

86 Posts

Re: PasswordBox Control

hi,

i can use in this PasswordTextBox just in code behind?

how do i make the textbox from xaml to behave like PasswordTextBox?

thanks.  

doolittle
doolittle

Member

Member

74 points

26 Posts

Re: PasswordBox Control

For the moment Silverlight does not have a PasswordTextBox 'out of the box'.
You have some options if you want one:

- Get some third party controls (from componentone for instance)
- Use the class from this forum post (link to version a few posts higher...)
- Wait for the next release of Silverlight (and prey it will contain a PasswordTextBox)

 

GearWorld
GearWorld

Participant

Participant

840 points

1,101 Posts

Re: PasswordBox Control

Hope they'll just make a property which we can just set the caracter we want for the mask
Don't make another control please.

 

mhaggag
mhaggag

Member

Member

308 points

59 Posts

Re: PasswordBox Control

Yes, the PasswordChar property exists. The Silverlight PasswordBox API is almost identical to that of WPF PasswordBox.

Muhammad Haggag.
SDE, Silverlight (Text feature team)

GearWorld
GearWorld

Participant

Participant

840 points

1,101 Posts

Re: PasswordBox Control

Yeah PasswordChar that's great but not a nother control called PasswordBox.  Comon, just let us use TextBox having the PasswordChar property.
That's what I was trying to say why the use of another control just for that ?

 

DevTricks
DevTricks

Member

Member

4 points

3 Posts

Re: PasswordBox Control

The 0 lines of code way : http://silverlight.net/forums/p/22876/80771.aspx

enjoy :)

GearWorld
GearWorld

Participant

Participant

840 points

1,101 Posts

Re: PasswordBox Control

Now that RC0 has the PasswordBox.  I'm happy like a baby :)  Works like a charm
But I didn't see any PasswordChar property available in Blend 2 yet

 

mhaggag
mhaggag

Member

Member

308 points

59 Posts

Re: PasswordBox Control

The reason PasswordBox is a separate control is that it's conceptually different from a TextBox--for example, the WPF PasswordBox stores the password in an encrypted string, doesn't support Copy/Cut, and has a different API to that of a normal TextBox. We follow WPF for compatibility (but we don't have encrypted storage so far).

As for the PasswordChar property in Blend, can't help with that, sorry. Can you open a new thread for that with "Blend" on the title? That way folks with Blend experience can chime in.

Muhammad Haggag.
SDE, Silverlight (Text feature team)
  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities