Search code examples
wpfxamltextboxwindows-phone-8.1passwordbox

Hiding the text of a TextBox control without using a PasswordBox


I am using a TextBox control for the user input in my Windows Phone 8.1 app.
How can I hide the characters as user gives input?

I am not using a PasswordBox because the defined InputScope is "Number" which is not possible in a PasswordBox.

While searching for a solution on the internet I found the only way by customizing the TextBox with the help of an UserControl.

Is there any easier way to do this without creating any UserControl?
Following is my code snippet:

In XAML page:

<TextBox Text="{Binding CardNo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    MaxLength="17"
    x:Name="CardNoTextBox"
    InputScope="Number"
    Margin="70,5"
    PlaceholderText="Enter Your Card Number"
    TextChanged="CardNoTextBox_TextChanged"
    BorderBrush="Gray"
    BorderThickness="2"
    FontSize="20"/>

In code behind (xaml.cs):

private void CardNoTextBox_TextChanged(object sender, RoutedEventArgs routedEventArgs)
{
    if (IsTextAllowed(CardNoTextBox.Text))
    {
        if (CardNoTextBox.Text.Length == 5)
        {
            if (CardNoTextBox.Text[4] != ' ')
            {
                string text = CardNoTextBox.Text.Insert(4, " ");
                CardNoTextBox.Text = text;
                CardNoTextBox.Select(CardNoTextBox.Text.Length, 0);
            }
        }

        if (CardNoTextBox.Text.Length == 12)
        {
            if (CardNoTextBox.Text[11] != ' ')
            {
                string text = CardNoTextBox.Text.Insert(11, " ");
                CardNoTextBox.Text = text;
                CardNoTextBox.Select(CardNoTextBox.Text.Length, 0);
            }
        }
    }
    else
    {
        CardNoTextBox.Text = "";
    }
}

Solution

  • After spending hours in finding an easier way I got an amazing solution. Hope this would help others too.
    I simply added the following value to the FontFamily property of my TextBox control:

    FontFamily="ms-appx:///Assets/PassDot.ttf#PassDot"
    

    And gave the size of font 35,

    FontSize="35"
    

    This works just fine for my project.