WPF Maskable TextBox for Numeric or Text Values

Download WPF Maskable TextBox Test Application

Introduction

This article describes how to enhance the WPF TextBox and make it accept just maskable numeric decimal, integer or text values. Maskable wpf text box also allows setting minimum and maximum values.
Maskable TextBox allows us to apply mask to a TextBox. This article demonstrates how to use the Maskable TextBox in a WPF application. Also you can download C# and Xaml code.

1
namespace xxx.Wpf.HelperClasses { public class TextBoxMaskBehavior


Here Sample Screenshot of our test application about using any mask type of wpf textbox.

WPF Maskable Text Box Test Application

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
private static void TextBox_PreviewTextInput(object sender,
    System.Windows.Input.TextCompositionEventArgs e)
{
    TextBox _this = (sender as TextBox);
    bool isValid = IsSymbolValid(GetMask(_this), e.Text);
    e.Handled = !isValid;
    if (isValid)
    {
 
        int caret = _this.CaretIndex;
        string text = _this.Text;
        bool textInserted = false;
        int selectionLength = 0;
 
        if (_this.SelectionLength > 0)
        {
            text = text.Substring(0, _this.SelectionStart) +
                    text.Substring(_this.SelectionStart + _this.SelectionLength);
            caret = _this.SelectionStart;
        }
        if (e.Text == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator && 
         text.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
        {
            int ind = text.IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
            caret = ind;
        }
        if (e.Text == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
        {
            while (true)
            {
                int ind = text.IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
                if (ind == -1)
                    break;
 
                text = text.Substring(0, ind) + text.Substring(ind + 1);
                if (caret > ind)
                    caret--;
            }
 
            if (caret == 0)
            {
                text = "0" + text;
                caret++;
            }
            else
            {
                if (caret == 1 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign)
                {
                    text = NumberFormatInfo.CurrentInfo.NegativeSign + "0" + text.Substring(1);
                    caret++;
                }
            }
 
            if (caret == text.Length)
            {
                selectionLength = 1;
                textInserted = true;
                text = text + NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "0";
                caret++;
            }
        }
        else if (e.Text == NumberFormatInfo.CurrentInfo.NegativeSign)
        {
            textInserted = true;
            if (_this.Text.Contains(NumberFormatInfo.CurrentInfo.NegativeSign))
            {
                text = text.Replace(NumberFormatInfo.CurrentInfo.NegativeSign, string.Empty);
                if (caret != 0)
                    caret--;
            }
            else
            {
                text = NumberFormatInfo.CurrentInfo.NegativeSign + _this.Text;
                caret++;
            }
        }
 
        if (!textInserted)
        {
            text = text.Substring(0, caret) + e.Text +
                ((caret < _this.Text.Length) ? text.Substring(caret) : string.Empty);
 
            caret++;
        }
 
        try
        {
            double val = Convert.ToDouble(text);
            double newVal = ValidateLimits(GetMinimumValue(_this), GetMaximumValue(_this), val);
            if (val != newVal)
            {
                text = newVal.ToString();
            }
            else if (val == 0)
            {
                if (!text.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
                    text = "0";
            }
        }
        catch
        {
            text = "0";
        }
 
        while (text.Length > 1 && text[0] == '0' && string.Empty + text[1] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
        {
            text = text.Substring(1);
            if (caret > 0)
                caret--;
        }
 
        while (text.Length > 2 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign && text[1] == '0' && string.Empty + text[2] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
        {
            text = NumberFormatInfo.CurrentInfo.NegativeSign + text.Substring(2);
            if (caret > 1)
                caret--;
        }
 
        if ((GetMask(_this) == MaskType.Decimal) && text.Length > 3)
        {
            int indexSep = text.IndexOf(NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator);
            if (indexSep > 0)
            {
                string sepLast = text.Substring(indexSep + 1);
                int length = sepLast.Length;
                if (length > 2)
                    text = text.Substring(0, indexSep) + NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator + sepLast.Substring(0, 2);
            }
        }
 
        if ((GetMask(_this) == MaskType.Decimal) && text.Length > _this.MaxLength)
        {
            int indexSep = text.IndexOf(NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator);
            int length = 0;
            if (indexSep > 0)
            {
                string sepLast = text.Substring(indexSep + 1);
                length = sepLast.Length + 1;
 
                if ((text.Length - length) >_this.MaxLength)
                {
                    text = text.Substring(0, _this.MaxLength) + NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator + sepLast.Substring(0, length - 1);
                }
            }
            if ((text.Length - length) > _this.MaxLength)
            {
                text = text.Substring(0, _this.MaxLength);
            }
        }
 
        if ((GetMask(_this) == MaskType.Integer) && text.Length >_this.MaxLength)
        {
            text = text.Substring(0, _this.MaxLength);
        }
        if ((GetMask(_this) == MaskType.Number) && text.Length > _this.MaxLength)
        {
            text = text.Substring(0, _this.MaxLength);
        }
        if ((GetMask(_this) == MaskType.Any) && text.Length > _this.MaxLength)
        {
            text = text.Substring(0, _this.MaxLength);
        }
 
        if (GetMask(_this) == MaskType.Decimal)
        {
            if (text.Length > 0)
            {
                int firstDotNumber = 0;
                if (text.Contains(NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator))
                {
                    var a = text.Split(NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator.ToCharArray());
                    firstDotNumber = (a.Length - 1);
                }
                text = text.Replace(NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator, "");
                var style = NumberStyles.Number | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
                var culture = CultureInfo.GetCultureInfo("tr-TR");
                decimal d = Decimal.Parse(text, style, culture.NumberFormat);
                text = string.Format("{0:N}", d);
 
                int lastDotNumber = 0;
                if (text.Contains(NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator))
                {
                    var a = text.Split(NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator.ToCharArray());
                    lastDotNumber = (a.Length - 1);
                }
 
                if (lastDotNumber > firstDotNumber)
                {
                    caret++;
                }
            }
        }
        if (caret > text.Length)
            caret = text.Length;
 
        _this.Text = text;
        _this.CaretIndex = caret;
        _this.SelectionStart = caret;
        _this.SelectionLength = selectionLength;
        e.Handled = true;
    }
}

Also , we are identify Mask Type for our Masked behaviour class.

1
2
3
4
5
6
7
public enum MaskType
{
    Any,
    Integer,
    Decimal,
    Number
}

And Finally, Lets Create a MaskedTextBox
Now, we are locate mask for the WPF TextBox like below.

1
2
3
xmlns:commonWPF="clr-namespace:xxx.Wpf.HelperClasses" 
 
commonWPF:TextBoxMaskBehavior.Mask="Decimal"


Views (5265)

Tags: , , ,

3 Comments to "WPF Maskable TextBox for Numeric or Text Values"

  1. I will right away grab your rss as I can not find your e-mail subscription link or e-newsletter service. Do you have any? Kindly let me know in order that I could subscribe. Thanks.

  2. DSM says:

    This is what I am looking for but would be great if the example could be downloaded to VS 10 project. Is it possible?

  3. Serhat Tural Serhat Tural says:

    Hi DSM,

    You can download sample application, it is created on Visual Studio 2010.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

SoftCodeArticle was formed to help developers solve common software issues.