syncfusion-winui-masked-textbox

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing MaskedTextBox

实现MaskedTextBox

Guide for implementing Syncfusion® WinUI MaskedTextBox (SfMaskedTextBox) — an advanced input control that restricts and formats user input using customizable mask patterns, supporting both simple and regex-based masks with error indication and validation.
本指南用于实现Syncfusion® WinUI MaskedTextBox(SfMaskedTextBox)——这是一款高级输入控件,可通过可自定义的掩码模式限制并格式化用户输入,支持简单掩码和基于RegEx的掩码,同时提供错误提示和校验功能。

When to Use This Skill

何时使用本技能

Use this skill when you need to:
  • Create masked input fields with pattern validation in WinUI applications
  • Implement phone number fields with formatted input like (555) 123-4567
  • Add email validation using regex patterns
  • Create date entry fields with visual placeholders
  • Build product key inputs like XXXXX-XXXXX-XXXXX
  • Validate SSN, credit cards, IP addresses with custom masks
  • Show error indication with icons and tooltips
  • Customize prompt characters for empty fields
  • Format values for display and clipboard operations
  • Add headers and descriptions to input fields
This skill covers complete MaskedTextBox implementation including mask types, validation, error handling, and customization.
当你需要实现以下需求时可使用本技能:
  • 在WinUI应用中创建带模式校验的掩码输入框
  • 实现手机号输入框,支持如(555) 123-4567的格式化输入
  • 通过RegEx模式添加邮箱校验
  • 创建带可视化占位符的日期录入框
  • 构建形如XXXXX-XXXXX-XXXXX的产品密钥输入框
  • 通过自定义掩码校验SSN、信用卡号、IP地址
  • 通过图标和工具提示展示错误提示
  • 自定义空白输入框的提示字符
  • 为展示和剪贴板操作格式化数值
  • 为输入框添加标题和描述
本技能覆盖MaskedTextBox的完整实现,包括掩码类型、校验、错误处理和自定义配置。

Component Overview

组件概述

Control:
SfMaskedTextBox

Namespace:
Syncfusion.UI.Xaml.Editors

NuGet Package:
Syncfusion.Editors.WinUI

Platform: WinUI 3 Desktop (.NET 5+)
The SfMaskedTextBox control provides:
  • Mask Types - Simple (fixed-length) and RegEx (variable-length) patterns
  • Simple Masks - Built-in elements: 0 (digit), L (letter), A (alphanumeric), etc.
  • RegEx Masks - Full regex pattern support for complex validation
  • Prompt Character - Customizable placeholder character (default '_')
  • Value Formatting - Control how values appear with literals and prompts
  • Error Indication - Built-in error types (Warning, Success, Critical, etc.)
  • Custom Errors - Custom icons and border colors for validation
  • Header & Description - Labels and help text for better UX
  • Events - ValueChanging and ValueChanged for real-time validation
控件:
SfMaskedTextBox

命名空间:
Syncfusion.UI.Xaml.Editors

NuGet包:
Syncfusion.Editors.WinUI

支持平台: WinUI 3 桌面端 (.NET 5+)
SfMaskedTextBox控件提供以下能力:
  • 掩码类型:支持简单(固定长度)和RegEx(可变长度)两种模式
  • 简单掩码:内置元素:0(数字)、L(字母)、A(字母数字)等
  • RegEx掩码:支持完整的RegEx模式,可实现复杂校验
  • 提示字符:可自定义占位符(默认值为'_')
  • 数值格式化:可控制文本和提示字符的展示方式
  • 错误提示:内置错误类型(警告、成功、严重错误等)
  • 自定义错误:支持自定义校验用的图标和边框颜色
  • 标题和描述:支持标签和帮助文本,提升用户体验
  • 事件:提供ValueChanging和ValueChanged事件,支持实时校验

Control Structure

控件结构

SfMaskedTextBox
├── Header (optional) - Label above the control
├── Input Area - Masked text entry with prompt characters
├── Error Icon (optional) - Validation feedback indicator
└── Description (optional) - Help text below the control
SfMaskedTextBox
├── 标题(可选)- 控件上方的标签
├── 输入区域 - 带提示字符的掩码文本录入区
├── 错误图标(可选)- 校验反馈指示器
└── 描述(可选)- 控件下方的帮助文本

Documentation and Navigation Guide

文档和导航指南

Getting Started

入门指南

📄 Read: references/getting-started.md
  • Installation and NuGet package setup
  • Adding control in XAML and code-behind
  • Namespace imports
  • Simple mask example (date pattern)
  • RegEx mask example (email pattern)
  • Setting prompt character
  • Setting value property
📄 阅读: references/getting-started.md
  • 安装和NuGet包配置
  • 在XAML和代码后置中添加控件
  • 命名空间导入
  • 简单掩码示例(日期模式)
  • RegEx掩码示例(邮箱模式)
  • 设置提示字符
  • 设置value属性

Mask Types

掩码类型

📄 Read: references/mask-types.md
  • Simple mask type for fixed-length inputs
  • Simple mask elements (0, 9, #, L, ?, C, A, <, >)
  • Element descriptions and usage
  • RegEx mask type for variable-length inputs
  • RegEx pattern elements and syntax
  • Phone number mask examples
  • Email pattern examples
  • Product key patterns
  • Custom mask creation
📄 阅读: references/mask-types.md
  • 适用于固定长度输入的简单掩码类型
  • 简单掩码元素(0, 9, #, L, ?, C, A, <, >)
  • 元素说明和使用方法
  • 适用于可变长度输入的RegEx掩码类型
  • RegEx模式元素和语法
  • 手机号掩码示例
  • 邮箱模式示例
  • 产品密钥模式
  • 自定义掩码创建

Value Formatting

数值格式化

📄 Read: references/value-formatting.md
  • Value property usage
  • ValueMaskFormat options
  • IncludeLiterals format
  • IncludePrompt format
  • ExcludePromptAndLiterals format
  • Clipboard copy behavior
  • Paste operations
  • Retrieving formatted vs raw values
📄 阅读: references/value-formatting.md
  • Value属性使用方法
  • ValueMaskFormat选项
  • IncludeLiterals格式
  • IncludePrompt格式
  • ExcludePromptAndLiterals格式
  • 剪贴板复制行为
  • 粘贴操作
  • 获取格式化值和原始值

Error Indication

错误提示

📄 Read: references/error-indication.md
  • ErrorType property
  • Built-in error types (None, Default, Warning, Information, Critical, Success)
  • Setting error type based on validation
  • Custom error type
  • CustomErrorIcon property
  • CustomErrorBorderBrush property
  • ErrorContent property for tooltip messages
  • Validation scenarios
📄 阅读: references/error-indication.md
  • ErrorType属性
  • 内置错误类型(None、Default、Warning、Information、Critical、Success)
  • 根据校验结果设置错误类型
  • 自定义错误类型
  • CustomErrorIcon属性
  • CustomErrorBorderBrush属性
  • 用于工具提示消息的ErrorContent属性
  • 校验场景

Customization

自定义配置

📄 Read: references/customization.md
  • Header property for labels
  • HeaderTemplate for custom header design
  • Description property for help text
  • Styling the control
  • Custom templates
  • Visual appearance customization
📄 阅读: references/customization.md
  • 用于标签的Header属性
  • 用于自定义标题设计的HeaderTemplate
  • 用于帮助文本的Description属性
  • 控件样式设置
  • 自定义模板
  • 视觉外观自定义

Events

事件

📄 Read: references/events.md
  • ValueChanging event (before change)
  • ValueChanged event (after change)
  • Event arguments and properties
  • Validation with events
  • Real-time feedback
  • Canceling input changes
📄 阅读: references/events.md
  • ValueChanging事件(值变更前触发)
  • ValueChanged事件(值变更后触发)
  • 事件参数和属性
  • 基于事件的校验
  • 实时反馈
  • 取消输入变更

Quick Start Example

快速入门示例

Phone Number Input with Validation

带校验的手机号输入

xaml
<syncfusion:SfMaskedTextBox Width="200"
                            Header="Phone Number"
                            MaskType="Simple"
                            Mask="(000) 000-0000"
                            PromptChar="#"
                            ErrorType="Warning"
                            Description="Enter your 10-digit phone number"
                            ValueChanging="OnPhoneNumberChanging" />
csharp
private void OnPhoneNumberChanging(object sender, MaskedTextBoxValueChangingEventArgs e)
{
    // Show success icon for valid input, warning otherwise
    var maskedTextBox = sender as SfMaskedTextBox;
    maskedTextBox.ErrorType = e.IsValid ? ErrorType.Success : ErrorType.Warning;
}
xaml
<syncfusion:SfMaskedTextBox Width="200"
                            Header="Phone Number"
                            MaskType="Simple"
                            Mask="(000) 000-0000"
                            PromptChar="#"
                            ErrorType="Warning"
                            Description="Enter your 10-digit phone number"
                            ValueChanging="OnPhoneNumberChanging" />
csharp
private void OnPhoneNumberChanging(object sender, MaskedTextBoxValueChangingEventArgs e)
{
    // 输入有效时展示成功图标,否则展示警告
    var maskedTextBox = sender as SfMaskedTextBox;
    maskedTextBox.ErrorType = e.IsValid ? ErrorType.Success : ErrorType.Warning;
}

Common Patterns

常用模式

Pattern 1: Date Entry with Simple Mask

模式1:简单掩码实现日期录入

xaml
<syncfusion:SfMaskedTextBox Width="200"
                            Header="Date of Birth"
                            MaskType="Simple"
                            Mask="00/00/0000"
                            Value="12/31/1990" />
Use when: Fixed-format date entry (MM/DD/YYYY)
xaml
<syncfusion:SfMaskedTextBox Width="200"
                            Header="Date of Birth"
                            MaskType="Simple"
                            Mask="00/00/0000"
                            Value="12/31/1990" />
适用场景: 固定格式的日期录入(月/日/年)

Pattern 2: Email Validation with RegEx

模式2:RegEx实现邮箱校验

xaml
<syncfusion:SfMaskedTextBox Width="300"
                            Header="Email Address"
                            MaskType="RegEx"
                            Mask="[A-Za-z0-9._%-]+@[A-Za-z0-9]+\.[A-Za-z]{2,3}"
                            ErrorType="Information"
                            ValueChanging="OnEmailValidation" />
Use when: Variable-length input with pattern validation
xaml
<syncfusion:SfMaskedTextBox Width="300"
                            Header="Email Address"
                            MaskType="RegEx"
                            Mask="[A-Za-z0-9._%-]+@[A-Za-z0-9]+\.[A-Za-z]{2,3}"
                            ErrorType="Information"
                            ValueChanging="OnEmailValidation" />
适用场景: 带模式校验的可变长度输入

Pattern 3: Product Key with Uppercase Conversion

模式3:带大写转换的产品密钥输入

xaml
<syncfusion:SfMaskedTextBox Width="300"
                            Header="Product Key"
                            MaskType="Simple"
                            Mask=">AAAAA-AAAAA-AAAAA-AAAAA"
                            Description="Format: XXXXX-XXXXX-XXXXX-XXXXX" />
Use when: Formatted serial numbers or license keys (> converts to uppercase)
xaml
<syncfusion:SfMaskedTextBox Width="300"
                            Header="Product Key"
                            MaskType="Simple"
                            Mask=">AAAAA-AAAAA-AAAAA-AAAAA"
                            Description="Format: XXXXX-XXXXX-XXXXX-XXXXX" />
适用场景: 格式化序列号或许可证密钥(>符号会将输入转为大写)

Pattern 4: Custom Error with Icon and Border

模式4:带自定义图标和边框的错误提示

xaml
<syncfusion:SfMaskedTextBox Width="250"
                            MaskType="Simple"
                            Mask="000-00-0000"
                            ErrorType="Custom"
                            CustomErrorIcon="ms-appx:///Assets/ErrorIcon.png"
                            CustomErrorBorderBrush="Red"
                            ErrorContent="Invalid SSN format" />
Use when: Need custom branding for error states
xaml
<syncfusion:SfMaskedTextBox Width="250"
                            MaskType="Simple"
                            Mask="000-00-0000"
                            ErrorType="Custom"
                            CustomErrorIcon="ms-appx:///Assets/ErrorIcon.png"
                            CustomErrorBorderBrush="Red"
                            ErrorContent="Invalid SSN format" />
适用场景: 需要自定义错误状态品牌样式的场景

Pattern 5: Credit Card with Formatted Display

模式5:带格式化展示的信用卡输入

xaml
<syncfusion:SfMaskedTextBox Width="200"
                            Header="Credit Card"
                            MaskType="Simple"
                            Mask="0000 0000 0000 0000"
                            ValueMaskFormat="ExcludePromptAndLiterals" />
Use when: Display formatted input but return raw values
xaml
<syncfusion:SfMaskedTextBox Width="200"
                            Header="Credit Card"
                            MaskType="Simple"
                            Mask="0000 0000 0000 0000"
                            ValueMaskFormat="ExcludePromptAndLiterals" />
适用场景: 需要展示格式化输入但返回原始值用于处理的场景

Key Properties

核心属性

PropertyTypeDescription
MaskstringThe pattern used to restrict input (e.g., "00/00/0000")
MaskTypeMaskedTextBoxMaskTypeSimple or RegEx mask type
ValuestringCurrent input value
PromptCharcharCharacter shown for empty mask positions (default '_')
ValueMaskFormatMaskedTextBoxValueMaskFormatHow value is formatted (literals, prompts)
ErrorTypeErrorTypeValidation feedback type (None, Warning, Success, etc.)
CustomErrorIconImageSourceCustom error icon for Custom error type
CustomErrorBorderBrushBrushCustom border brush for errors
ErrorContentobjectTooltip content shown on error icon hover
HeaderobjectLabel displayed above the control
HeaderTemplateDataTemplateCustom template for header
DescriptionobjectHelp text displayed below the control
属性类型描述
Maskstring用于限制输入的模式(例如 "00/00/0000")
MaskTypeMaskedTextBoxMaskType掩码类型:简单掩码或RegEx掩码
Valuestring当前输入值
PromptCharchar空白掩码位置展示的字符(默认值为'_')
ValueMaskFormatMaskedTextBoxValueMaskFormat数值的格式化方式(文本、提示字符)
ErrorTypeErrorType校验反馈类型(None、Warning、Success等)
CustomErrorIconImageSource自定义错误类型对应的自定义错误图标
CustomErrorBorderBrushBrush错误状态的自定义边框画笔
ErrorContentobject错误图标悬停时展示的工具提示内容
Headerobject控件上方展示的标签
HeaderTemplateDataTemplate标题的自定义模板
Descriptionobject控件下方展示的帮助文本

Common Use Cases

常见使用场景

Use Case 1: Form with Multiple Validated Inputs

场景1:带多个校验输入框的表单

Create a registration form with phone, email, and SSN fields, each with appropriate masks and validation icons.
创建包含手机号、邮箱和SSN字段的注册表单,每个字段都配置对应的掩码和校验图标。

Use Case 2: International Phone Numbers

场景2:国际手机号录入

Use RegEx masks to support various international phone number formats with country codes.
使用RegEx掩码支持多种带国家代码的国际手机号格式。

Use Case 3: Credit Card Entry

场景3:信用卡录入

Implement credit card input with formatted display (groups of 4 digits) and raw value for processing.
实现信用卡输入功能,支持格式化展示(每4位数字一组)并返回原始值用于后续处理。

Use Case 4: IP Address Entry

场景4:IP地址录入

Use simple mask "000.000.000.000" with validation to ensure each octet is between 0-255.
使用简单掩码"000.000.000.000"配合校验,确保每个网段的值在0-255之间。

Use Case 5: Time Entry

场景5:时间录入

Create time input fields with "00:00 >LL" mask supporting 24-hour format with AM/PM indicator.
创建时间输入框,使用"00:00 >LL"掩码支持带AM/PM标识的24小时格式。

Use Case 6: Product Serial Number Scanner

场景6:产品序列号扫描器

Implement barcode-compatible input with uppercase conversion and segment validation.
实现兼容条形码的输入功能,支持大写转换和分段校验。

Use Case 7: Custom Validation Messages

场景7:自定义校验消息

Show contextual error messages based on specific validation rules using ErrorContent.
使用ErrorContent基于特定校验规则展示上下文相关的错误消息。

Use Case 8: Multi-Language Support

场景8:多语言支持

Use regex patterns that adapt to different locale requirements for phone numbers and postal codes.
使用RegEx模式适配不同地区的手机号和邮政编码格式要求。

Troubleshooting

故障排查

Issue: Mask not accepting input
  • Verify mask pattern matches expected input type (digits vs letters)
  • Check MaskType is set correctly (Simple vs RegEx)
  • Ensure mask elements are valid for chosen MaskType
Issue: Value property not updating
  • Use ValueChanged event to track changes
  • Check ValueMaskFormat if retrieved value seems wrong
  • Ensure two-way binding:
    Value="{x:Bind Property, Mode=TwoWay}"
Issue: Error icon not appearing
  • Set ErrorType to a value other than None
  • For Custom type, provide CustomErrorIcon
  • Ensure control has sufficient width to display icon
Issue: RegEx mask not validating correctly
  • Escape special characters in XAML (use
    \\.
    for literal dot)
  • Test regex pattern independently before using in mask
  • Remember RegEx masks are for variable-length input
Issue: Prompt character visible in value
  • Adjust ValueMaskFormat property
  • Use ExcludePromptAndLiterals to get clean value
  • Check if prompts are intentionally included
Issue: Header or Description not showing
  • Verify property is set in XAML or code
  • Check control height allows space for header/description
  • Ensure HeaderTemplate syntax is correct if customizing

Related Skills:
  • Parent Library: implementing-syncfusion-winui-components
  • WinUI Editors: Coming soon
  • WinUI Data Validation: Coming soon
问题:掩码不接受输入
  • 确认掩码模式与预期输入类型匹配(数字vs字母)
  • 检查MaskType是否正确设置(简单掩码vs RegEx)
  • 确保所选MaskType对应的掩码元素合法
问题:Value属性不更新
  • 使用ValueChanged事件跟踪变更
  • 如果获取的值不符合预期,检查ValueMaskFormat配置
  • 确保双向绑定配置正确:
    Value="{x:Bind Property, Mode=TwoWay}"
问题:错误图标不展示
  • 将ErrorType设置为None以外的值
  • 若使用Custom类型,需提供CustomErrorIcon
  • 确保控件有足够宽度展示图标
问题:RegEx掩码校验异常
  • 在XAML中转移特殊字符(字面量点使用
    \\.
  • 在掩码中使用前先单独测试RegEx模式
  • 注意RegEx掩码适用于可变长度输入
问题:提示字符出现在返回值中
  • 调整ValueMaskFormat属性
  • 使用ExcludePromptAndLiterals获取纯净值
  • 确认是否是有意保留提示字符
问题:标题或描述不展示
  • 确认XAML或代码中已设置对应属性
  • 检查控件高度是否有足够空间展示标题/描述
  • 若使用自定义HeaderTemplate,确认语法正确

相关技能:
  • 父级库:implementing-syncfusion-winui-components
  • WinUI编辑器:即将上线
  • WinUI数据校验:即将上线