syncfusion-wpf-maskedtextbox
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syncfusion WPF MaskedTextBox (SfMaskedEdit)
实现Syncfusion WPF MaskedTextBox(SfMaskedEdit)
The WPF MaskedTextBox (SfMaskedEdit) is an advanced input control that restricts user input to specific types using mask patterns. It's ideal for creating templates for phone numbers, IP addresses, product IDs, dates, and other formatted data entry.
WPF MaskedTextBox(SfMaskedEdit)是一款高级输入控件,可通过掩码模式将用户输入限制为特定类型。它非常适合为电话号码、IP地址、产品ID、日期和其他格式化数据输入创建模板。
When to Use This Skill
何时使用本技能
Use this skill when you need to:
- Restrict input to specific formats without custom validation
- Implement formatted input fields for phone numbers, emails, dates, currency
- Create mask patterns using Simple or RegEx mask types
- Validate user input on key press or lost focus
- Format values with or without literals and prompt characters
- Display error indicators for invalid input
- Add watermarks to guide user input
- Customize appearance including colors, borders, and themes
- Support RTL layouts for international applications
- Handle value changes with event notifications
当你需要以下功能时,可使用本技能:
- 无需自定义验证即可限制输入为特定格式
- 为电话号码、邮箱、日期、货币实现格式化输入字段
- 使用Simple或RegEx掩码类型创建掩码模式
- 在按键或失去焦点时验证用户输入
- 包含或不包含文字和提示字符的情况下格式化值
- 为无效输入显示错误指示器
- 添加水印以引导用户输入
- 自定义外观,包括颜色、边框和主题
- 为国际应用支持RTL布局
- 通过事件通知处理值变更
Component Overview
组件概述
SfMaskedEdit provides:
- Multiple mask types: Simple and RegEx patterns
- Flexible validation: KeyPress or LostFocus validation modes
- Value formatting: Include/exclude prompts and literals
- Visual feedback: Error borders, prompt characters, watermarks
- Full customization: Colors, themes, templates
- MVVM support: Data binding and property change notifications
Assembly: ,
Namespace:
Syncfusion.SfInput.WPFSyncfusion.SfShared.WPFNamespace:
Syncfusion.Windows.Controls.InputSfMaskedEdit 提供以下功能:
- 多种掩码类型:Simple和RegEx模式
- 灵活的验证:KeyPress或LostFocus验证模式
- 值格式化:包含/排除提示和文字
- 视觉反馈:错误边框、提示字符、水印
- 完全自定义:颜色、主题、模板
- MVVM支持:数据绑定和属性变更通知
程序集:、
命名空间:
Syncfusion.SfInput.WPFSyncfusion.SfShared.WPF命名空间:
Syncfusion.Windows.Controls.InputDocumentation and Navigation Guide
文档与导航指南
Getting Started
入门指南
📄 Read: references/getting-started.md
- Assembly deployment and NuGet installation
- Adding SfMaskedEdit via designer, XAML, and C#
- Basic configuration and setup
- First masked textbox example
- Handling ValueChanged events
📄 阅读:references/getting-started.md
- 程序集部署与NuGet安装
- 通过设计器、XAML和C#添加SfMaskedEdit
- 基础配置与设置
- 首个掩码文本框示例
- 处理ValueChanged事件
Mask Patterns and Input Restriction
掩码模式与输入限制
📄 Read: references/mask-patterns-input-restriction.md
- Mask element reference ([], \d, \w, {n}, +, *, ?, etc.)
- Creating custom mask patterns
- Allow/restrict specific values with (?=) and (?!)
- Extensive mask examples (phone, email, currency, dates, etc.)
- Input validation modes (KeyPress vs LostFocus)
- Validation results and HasError property
- PromptChar and ShowPromptOnFocus configuration
📄 阅读:references/mask-patterns-input-restriction.md
- 掩码元素参考([]、\d、\w、{n}、+、*、?等)
- 创建自定义掩码模式
- 使用(?=)和(?!)允许/限制特定值
- 丰富的掩码示例(电话、邮箱、货币、日期等)
- 输入验证模式(KeyPress vs LostFocus)
- 验证结果与HasError属性
- PromptChar和ShowPromptOnFocus配置
Value Management
值管理
📄 Read: references/value-management.md
- Setting and getting Value property
- ValueMaskFormat options:
- ExcludePromptAndLiterals
- IncludeLiterals
- IncludePrompt
- IncludePromptAndLiterals
- Value change notifications
- Clipboard operations with formatted values
📄 阅读:references/value-management.md
- 设置与获取Value属性
- ValueMaskFormat选项:
- ExcludePromptAndLiterals
- IncludeLiterals
- IncludePrompt
- IncludePromptAndLiterals
- 值变更通知
- 带格式化值的剪贴板操作
Appearance and Customization
外观与自定义
📄 Read: references/appearance-customization.md
- Background, Foreground, and SelectionBrush
- CaretBrush and BorderBrush customization
- ErrorBorderBrush for validation feedback
- FlowDirection for RTL support
- Watermark and WatermarkTemplate
- Theme integration and styling
📄 阅读:references/appearance-customization.md
- 背景色、前景色与选择刷
- 光标刷与边框刷自定义
- 用于验证反馈的ErrorBorderBrush
- 用于RTL支持的FlowDirection
- 水印与WatermarkTemplate
- 主题集成与样式设置
Quick Start Example
快速入门示例
Phone Number Mask
电话号码掩码
xml
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<syncfusion:SfMaskedEdit
x:Name="phoneNumber"
Mask="\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}"
MaskType="RegEx"
Value="4553456789"
PromptChar="_"
Width="200"
Height="30"
ValueChanged="PhoneNumber_ValueChanged"/>
</Grid>
</Window>csharp
using Syncfusion.Windows.Controls.Input;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void PhoneNumber_ValueChanged(object sender, EventArgs e)
{
var maskedEdit = sender as SfMaskedEdit;
if (!maskedEdit.HasError)
{
// Use formatted value: (455) 345-6789
string formattedPhone = maskedEdit.Value;
}
}
}xml
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<syncfusion:SfMaskedEdit
x:Name="phoneNumber"
Mask="\([0-9]\d{2}\) [0-9]\d{2}-[0-9]\d{3}"
MaskType="RegEx"
Value="4553456789"
PromptChar="_"
Width="200"
Height="30"
ValueChanged="PhoneNumber_ValueChanged"/>
</Grid>
</Window>csharp
using Syncfusion.Windows.Controls.Input;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void PhoneNumber_ValueChanged(object sender, EventArgs e)
{
var maskedEdit = sender as SfMaskedEdit;
if (!maskedEdit.HasError)
{
// 使用格式化后的值: (455) 345-6789
string formattedPhone = maskedEdit.Value;
}
}
}Common Patterns
常见模式
Pattern 1: Email Validation
模式1:邮箱验证
xml
<syncfusion:SfMaskedEdit
Mask="[A-Za-z0-9._%-]+@[A-Za-z0-9]+\.[A-Za-z]{2,3}"
MaskType="RegEx"
Watermark="Enter email address"
ErrorBorderBrush="Red"/>xml
<syncfusion:SfMaskedEdit
Mask="[A-Za-z0-9._%-]+@[A-Za-z0-9]+\.[A-Za-z]{2,3}"
MaskType="RegEx"
Watermark="Enter email address"
ErrorBorderBrush="Red"/>Pattern 2: Currency Input
模式2:货币输入
xml
<syncfusion:SfMaskedEdit
Mask="$ \d+\.\d{2}"
MaskType="RegEx"
Value="1234.56"
ValueMaskFormat="IncludeLiterals"/>xml
<syncfusion:SfMaskedEdit
Mask="$ \d+\.\d{2}"
MaskType="RegEx"
Value="1234.56"
ValueMaskFormat="IncludeLiterals"/>Pattern 3: Date Input with Validation
模式3:带验证的日期输入
xml
<syncfusion:SfMaskedEdit
Mask="(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/\d{4}"
MaskType="RegEx"
ValidationMode="LostFocus"
PromptChar="X"
ShowPromptOnFocus="True"/>xml
<syncfusion:SfMaskedEdit
Mask="(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/\d{4}"
MaskType="RegEx"
ValidationMode="LostFocus"
PromptChar="X"
ShowPromptOnFocus="True"/>Pattern 4: Product Key
模式4:产品密钥
xml
<syncfusion:SfMaskedEdit
Mask="[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}"
MaskType="RegEx"
ValueMaskFormat="ExcludePromptAndLiterals"/>xml
<syncfusion:SfMaskedEdit
Mask="[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}-[A-Z\d]{5}"
MaskType="RegEx"
ValueMaskFormat="ExcludePromptAndLiterals"/>Pattern 5: Get Value Without Formatting
模式5:获取无格式的值
csharp
// Get only user-entered digits (no literals or prompts)
sfMaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals;
string digitsOnly = sfMaskedEdit.Value; // "4553456789"
// Get with formatting literals
sfMaskedEdit.ValueMaskFormat = MaskFormat.IncludeLiterals;
string formatted = sfMaskedEdit.Value; // "(455) 345-6789"csharp
// 仅获取用户输入的数字(不含文字或提示)
sfMaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals;
string digitsOnly = sfMaskedEdit.Value; // "4553456789"
// 获取带格式化文字的值
sfMaskedEdit.ValueMaskFormat = MaskFormat.IncludeLiterals;
string formatted = sfMaskedEdit.Value; // "(455) 345-6789"Key Properties
关键属性
| Property | Type | Description |
|---|---|---|
| Mask | string | Mask pattern (null = no mask) |
| MaskType | MaskType | Simple or RegEx (default: Simple) |
| Value | string | Current value with formatting based on ValueMaskFormat |
| ValueMaskFormat | MaskFormat | Include/exclude prompts and literals |
| ValidationMode | InputValidationMode | KeyPress or LostFocus (default: KeyPress) |
| HasError | bool | True if validation failed (read-only) |
| PromptChar | char | Character for missing input (default: '_') |
| ShowPromptOnFocus | bool | Show prompts on focus vs while typing |
| ErrorBorderBrush | Brush | Border color for validation errors (default: Red) |
| Watermark | object | Text shown when empty |
| WatermarkTemplate | DataTemplate | Custom template for watermark |
| 属性 | 类型 | 描述 |
|---|---|---|
| Mask | string | 掩码模式(null表示无掩码) |
| MaskType | MaskType | Simple或RegEx(默认:Simple) |
| Value | string | 当前值,格式基于ValueMaskFormat |
| ValueMaskFormat | MaskFormat | 包含/排除提示和文字 |
| ValidationMode | InputValidationMode | KeyPress或LostFocus(默认:KeyPress) |
| HasError | bool | 验证失败时为True(只读) |
| PromptChar | char | 缺失输入的占位字符(默认:'_') |
| ShowPromptOnFocus | bool | 获得焦点时是否显示提示(vs 输入时显示) |
| ErrorBorderBrush | Brush | 验证错误的边框颜色(默认:红色) |
| Watermark | object | 为空时显示的文本 |
| WatermarkTemplate | DataTemplate | 自定义水印模板 |
Common Mask Patterns
常见掩码模式
| Use Case | Mask Pattern |
|---|---|
| Positive/negative numbers | |
| Currency | |
| Percent | |
| |
| Phone (US) | |
| Credit Card | |
| Time (24h) | `(0[0-9] |
| Zip Code | |
| Product Key | |
| Hexadecimal | |
| 使用场景 | 掩码模式 |
|---|---|
| 正/负数 | |
| 货币 | |
| 百分比 | |
| 邮箱 | |
| 美国电话号码 | |
| 信用卡 | |
| 24小时制时间 | `(0[0-9] |
| 邮政编码 | |
| 产品密钥 | |
| 十六进制 | |
Common Use Cases
常见使用场景
Data Entry Forms
数据输入表单
Use SfMaskedEdit in forms requiring formatted input like contact information, financial data, or identification numbers. Reduces validation code and improves UX.
在需要格式化输入的表单中使用SfMaskedEdit,如联系信息、财务数据或身份识别号码。减少验证代码并提升用户体验。
Phone Number Collection
电话号码收集
Implement consistent phone number formatting across your application with automatic formatting and validation.
在应用中实现统一的电话号码格式,支持自动格式化与验证。
Financial Applications
金融应用
Enforce currency, decimal, and percentage formats for accounting and financial data entry.
为会计和金融数据输入强制使用货币、小数和百分比格式。
Product Registration
产品注册
Validate product keys, serial numbers, and license codes with custom patterns.
使用自定义模式验证产品密钥、序列号和许可证代码。
Date and Time Input
日期与时间输入
Create custom date/time formats beyond standard DatePicker controls with RegEx validation.
通过RegEx验证创建超出标准DatePicker控件的自定义日期/时间格式。
International Support
国际化支持
Use FlowDirection for RTL languages and customize masks for regional formats (dates, phone numbers).
使用FlowDirection适配RTL语言,为区域格式(日期、电话号码)自定义掩码。
Real-time Validation
实时验证
Validate input on each keystroke (KeyPress) or on field exit (LostFocus) based on UX requirements.
根据用户体验需求,在每次按键(KeyPress)或字段失焦(LostFocus)时验证输入。
Events
事件
| Event | Description |
|---|---|
| ValueChanged | Fires when Value property changes (based on ValidationMode) |
| LostFocus | Standard WPF event, useful with LostFocus validation mode |
| 事件 | 描述 |
|---|---|
| ValueChanged | 当Value属性变更时触发(基于ValidationMode) |
| LostFocus | 标准WPF事件,在LostFocus验证模式下非常实用 |
Best Practices
最佳实践
- Choose appropriate MaskType: Use RegEx for complex patterns, Simple for basic scenarios
- Set ValueMaskFormat early: Determine format before accessing Value property
- Provide visual feedback: Use ErrorBorderBrush and Watermark for better UX
- Match validation mode to UX: KeyPress for instant feedback, LostFocus for less intrusive validation
- Document custom patterns: Comment complex RegEx masks for maintainability
- Test edge cases: Verify behavior with empty input, partial input, and boundary values
- Use ShowPromptOnFocus: Enable for better visibility of expected input format
Next Steps: Choose a reference file above based on your needs, or start with getting-started.md for initial setup.
- 选择合适的MaskType:复杂模式使用RegEx,基础场景使用Simple
- 尽早设置ValueMaskFormat:在访问Value属性前确定格式
- 提供视觉反馈:使用ErrorBorderBrush和Watermark提升用户体验
- 匹配验证模式与用户体验:KeyPress用于即时反馈,LostFocus用于低干扰性验证
- 文档化自定义模式:为复杂的RegEx掩码添加注释以提升可维护性
- 测试边缘情况:验证空输入、部分输入和边界值的行为
- 启用ShowPromptOnFocus:开启后可更清晰地显示预期输入格式
下一步:根据需求选择上方的参考文件,或从getting-started.md开始进行初始设置。