Click here to Skip to main content
15,905,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have a XAML requirement to add dashes when user is entering ssn in a text box. I tried below code, am able to add dashes, but unable to delete dashes from text box. Whenever i try to delete or use back space hyphens are not deleted

What I have tried:

XAML:
XML
<Window x:Class="WpfApplication2.MainWindow"                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <grid>
    <TextBox HorizontalAlignment="Left" Height="23"                    Margin="10,10,0,0"
    TextWrapping="Wrap" Name="Txtssn"
    Text=""
                                 MaxLength="11"
                                 VerticalAlignment="Top"
                                 Width="120"
                                 TextChanged="TextBox_TextChanged"/>

C#:
C#
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var textBox = sender as TextBox;

            string data = textBox.Text;

            if (data.Length == 3)
            {
                string formattedSSN = data.Insert(3, "-");
                Txtssn.Text = formattedSSN.ToString();
                textBox.Focus();
                textBox.SelectionStart = textBox.Text.Length;
            }
            else if (data.Length == 6)
            {
                string formattedSSN = data.Insert(6, "-");
                Txtssn.Text = formattedSSN.ToString();
                textBox.Focus();
                textBox.SelectionStart = textBox.Text.Length;
}}}
Posted
Updated 29-Apr-18 16:50pm
v3

1 solution

In order to correctly add or remove the hyphen you should handle for example UIElement.KeyDown Event (System.Windows)[^] . In the event handler, check if the user is adding text or removing it (backspace pressed). Also you need to take into consideration if delete key is pressed and/or if an area of text is selected and the caret position in the text.

There are quite a few example, like How To Implement a Mask for a Text Box in W.P.F.[^]. However, perhaps the easiest way would be to use a ready made control from Extended WPF Toolkit™[^]
 
Share this answer
 

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