Элемент MaskedTextBox по сути представляет обычное текстовое поле. Однако данные элемент позволяет контролировать ввод пользователя и проверять его автоматически на наличие ошибок.
Чтобы контролировать вводимые в поле символы, надо задать маску. Для задания маски можно применять следующие символы:
0 : Позволяет вводить только цифры
9 : Позволяет вводить цифры и пробелы
# : Позволяет вводить цифры, пробелы и знаки ‘+’ и ‘-‘
L : Позволяет вводить только буквенные символы
? : Позволяет вводить дополнительные необязательные буквенные символы
A : Позволяет вводить буквенные и цифровые символы
. : Задает позицию разделителя целой и дробной части
, : Используется для разделения разрядов в целой части числа
: : Используется в временных промежутках – разделяет часы, минуты и секунды
/ : Используется для разделения дат
$ : Используется в качестве символа валюты
Чтобы задать маску, надо установить свойство Mask элемента. Найдя это свойство в окне свойств(Porperties), нажмем на него и нам отобразится окно для задания одного из стандартных шаблонов маски. В частности мы можем выбрать Phone number (Телефонный номер), который подразумевает ввод в текстовое поле только телефонного номера:
Теперь при запуске мы сможем ввести в текстовое поле только цифры, получив в итоге телефонный номер.
Теперь сделаем свою маску. Например, создадим маску для ввода инициалов имени и отчества и фамилий ограниченной длины в текстовое поле. Для этого присвоим свойству Mask значение L.L.L. . Тогда ввод в текстовое поле будет выглядеть следующим образом:
Данный элемент также представляет нам ряд свойств, которые можно использовать для управления вводом. Так, свойство BeepOnError при установке значения true подает звуковой сигнал при введении некорректного символа.
Свойство HidePromptOnLeave при установке в true при потери текстовым полем фокуса скрывает, указанные в PromptChar
Свойство PromptChar указывает на символ, который отображается в поле на месте ввода символов. По умолчанию стоит знак подчеркивания.
Свойство AsciiOnly при значении true позволяет вводить только asci-символы, то есть символы из диапазона A-Z и a-z.
Derives from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox
Represents a control that limits the input text to the format determined by the specified mask.
Note: This version of MaskedTextBox replaces the toolkit’s original control, providing a much more complete API. The original control is still available in the Xceed.Wpf.Toolkit.Obsolete namespace; see MaskedTextBox (obsolete version).
Masking Element | Description |
---|---|
Digit, required. This element will accept any single digit between 0 and 9. | |
9 | Digit or space, optional. |
# | Digit or space, optional. If this position is blank in the mask, it will be rendered as a space in the Text property. Plus (+) and minus (-) signs are allowed. |
L | Letter, required. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to a-zA-Z in regular expressions. |
? | Letter, optional. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to a-zA-Z? in regular expressions. |
& | Character, required. If the AsciiOnly property is set to true, this element behaves like the "L" element. |
C | Character, optional. Any non-control character. If the AsciiOnly property is set to true, this element behaves like the "?" element. |
A | Alphanumeric, optional. If the AsciiOnly property is set to true, the only characters it will accept are the ASCII letters a-z and A-Z. |
a | Alphanumeric, optional. If the AsciiOnly property is set to true, the only characters it will accept are the ASCII letters a-z and A-Z. |
. | Decimal placeholder. The actual display character used will be the decimal symbol appropriate to the format provider, as determined by the control’s FormatProvider property. |
, | Thousands placeholder. The actual display character used will be the thousands placeholder appropriate to the format provider, as determined by the control’s FormatProvider property. |
: | Time separator. The actual display character used will be the time symbol appropriate to the format provider, as determined by the control’s FormatProvider property. |
/ | Date separator. The actual display character used will be the date symbol appropriate to the format provider, as determined by the control’s FormatProvider property. |
$ | Currency symbol. The actual character displayed will be the currency symbol appropriate to the format provider, as determined by the control’s FormatProvider property. |
Shift up. Converts all characters that follow to uppercase. | |
Disable a previous shift up or shift down. | |
Escape. Escapes a mask character, turning it into a literal. "" is the escape sequence for a backslash. |
Property | Description |
---|---|
AutoMoveFocus | Gets or sets a value indicating if the focus can navigate in the appropriate flow direction (e.g., from one cell to another when a cell is being edited) when the cursor is at the beginning or end of the auto-select text box. (Inherited from Xceed.Wpf.Toolkit.AutoSelectTextBox) |
AutoSelectBehavior | Gets or sets a value indicating how the content of the auto-select text box is selected (Never or OnFocus). By default Never. |
BeepOnError | Gets or sets whether a beep sound will be played on error. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
FormatProvider | Gets or sets the format provider. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
HasParsingError | Gets whether the control has a parsing error. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
HasValidationError | Gets whether the control has a validation error. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
InsertKeyMode | Gets or sets a value representing the text insertion mode of the masked text box. |
IsMaskCompleted | Gets a value indicating if all required characters have been inputted into the mask. |
IsMaskFull | Gets a value indicating if all characters, required and optional, have been inputted into the mask. |
IsValueOutOfRange | Gets whether the control’s value is out of range. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
Mask | Gets or sets the input mask. |
MaskTextProvider | Gets the MaskedTextProvider that was used to mask the input text. |
MaxValue | Gets or sets the maximum value of the control. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
MinValue | Gets or sets the minimum value of the control. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
NullValue | Gets or sets the null value. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
PromptChar | Gets or sets the character that represents the positions in the masked text box that require user input. |
RejectInputOnFirstFailure | Gets or sets a value indicating if inputted text that is pasted into the masked text box can be rejected if it contains an invalid character for the corresponding mask position. |
ResetOnPrompt | Gets or sets a value indicating if the character at the current caret position should be reset when the prompt character is pressed. |
ResetOnSpace | Gets or sets a value indicating if the character at the current caret position should be reset when the space bar is pressed. |
RestrictToAscii | Gets or sets a value indicating if the masked text box accepts non-ASCII characters. |
SkipLiterals | Gets or sets a value indicating if literal values can be overwritten by their same values. |
Text | Content of the MaskedTextBox. (Inherited from System.Windows.Controls.TextBox) |
Value | Gets or sets the value of the MaskedTextBox. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
ValueDataType | Gets or sets the Type of the value. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
Event | Description |
---|---|
QueryTextFromValue | Raised when an attempt is made to convert the specified value into its string representation. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
QueryValueFromText | Raised when an attempt is made to extract a value from the specified text. (Inherited from Xceed.Wpf.Toolkit.Primitives.ValueRangeTextBox) |
Support this project, check out the Plus Edition.
Masking input to a WPF TextBox February 15, 2007
This blog is no longer actively maintained. The content is well over 5 years old – which is like 50 coder years. Use at your own risk!
How do you go about masking the input to a textbox. Say you wanted to allow numbers but not letters or any punctuation, how would you do it? Well the simplest way is to trap the TextChanged event…
This method is simple to understand (always a positive) but there are a few problems with this as I see it, namely..
- An additional TextChanged event is raised when input is rejected
- You can’t tell what the change was, you can only inspect the end result
- You have to re-implement the code that determines the correct caret position
This is not a great way to solve the original problem, because we’re basically hacking at the input after it’s already been accepted. Leaving us trying to fix the text and compensate for the changes in caret position. It’s easier to reject invalid characters as they’re presented. Let’s start by defining a very simple method for stripping out the input we don’t want..
This could be defined slightly more elegantly using a predicate..
We then need to identify the entry points to the control and for each one, identify how we will be notified about it’s use. For typical a TextBox these entry points might be:
- Typing into the TextBox
- Hook up to the PreviewTextInput event
It’s easy to implement and hook up the handlers for these events..
In some cases, you may need to support other scenarios (such as allowing users to Drag-and-Drop text onto it) and these can be dealt with in a similar fashion – identify an appropriate event, check the input, and if it’s invalid then prevent any further processing.