The Textbox in Silverlight currently does not support masking the text when entering for an example a password. This may be supported in the future, but for now a work around was needed. By using a couple event handlers in the the Silverlight control, along with a few public methods in a separate class, it can be done.
The following code needs to be in the Silverlight control that hosts your textbox that needs to be masked.
Public strPassword As String = ""
Private Sub txtPassword_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs)
Try
If e.Key = Key.Enter Then
btnLogon_Click(sender, e)
Exit Sub
End If
Catch ex As Exception
End Try
Try
Dim mpassword As New HidePassword
mpassword.ParentObject = Me
mpassword.hpKeyDown(e)
Catch ex As Exception
End Try
End Sub
Private Sub txtPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
Dim mpassword As New HidePassword
mpassword.ParentObject = Me
mpassword.hpTextChanged()
End Sub
Create a class called ‘HidePassword’ and populate with the following logic:
Public Class HidePassword
Private mText As String = String.Empty
Private mPasswordChar As Char = "*"
Private mIPAddress As String = ""
Public ParentObject As New Logon(mIPAddress)
Public Sub hpTextChanged()
If ParentObject.txtPassword.Text.Length >= ParentObject.strPassword.Length Then
ParentObject.strPassword += ParentObject.txtPassword.Text.Substring(ParentObject.strPassword.Length)
End If
DisplayMaskedCharacters()
End Sub
Public Sub hpKeyDown(ByVal e)
Dim cursorPosition As Integer = ParentObject.txtPassword.SelectionStart
Dim selectionLength As Integer = ParentObject.txtPassword.SelectionLength
' Handle Delete and Backspace Keys Appropriately
If e.Key = Key.Back Or e.Key = Key.Delete Then
If cursorPosition < ParentObject.strPassword.Length Then
Dim lengthToRemove As Integer = 1
If selectionLength > 0 Then lengthToRemove = selectionLength
ParentObject.strPassword = ParentObject.strPassword.Remove(cursorPosition, lengthToRemove)
End If
End If
ParentObject.txtPassword.Text = ParentObject.strPassword
If cursorPosition > ParentObject.strPassword.Length Then
ParentObject.txtPassword.Select(ParentObject.strPassword.Length, 0)
Else
ParentObject.txtPassword.Select(cursorPosition, 0)
End If
DisplayMaskedCharacters()
End Sub
Private Sub DisplayMaskedCharacters()
Dim cursorPosition As Integer = ParentObject.txtPassword.SelectionStart
' This changes the Text property of the base TextBox class to display all Asterisks in the control
ParentObject.txtPassword.Text = New String(mPasswordChar, ParentObject.strPassword.Length)
If cursorPosition > ParentObject.strPassword.Length Then
ParentObject.txtPassword.Select(ParentObject.strPassword.Length, 0)
Else
ParentObject.txtPassword.Select(cursorPosition, 0)
End If
End Sub