如何在NuGet Uranium UI的TextField中实现巴西CPF掩码?已试MaskedBehavior无效
解决Uranium UI TextField的CPF输入掩码问题
方案一:自定义CPF掩码Behavior
由于Xamarin Community Toolkit的MaskedBehavior和Uranium UI TextField兼容性不佳,直接自定义专属的CPF掩码行为更可靠:
using Microsoft.Maui.Controls; using System.Text.RegularExpressions; public class CpfMaskBehavior : Behavior<TextField> { protected override void OnAttachedTo(TextField bindable) { base.OnAttachedTo(bindable); bindable.TextChanged += OnTextChanged; } protected override void OnDetachingFrom(TextField bindable) { base.OnDetachingFrom(bindable); bindable.TextChanged -= OnTextChanged; } private void OnTextChanged(object sender, TextChangedEventArgs e) { if (sender is not TextField textField) return; // 过滤所有非数字字符 var cleanText = Regex.Replace(e.NewTextValue ?? string.Empty, @"[^\d]", ""); var formattedText = string.Empty; // 应用CPF格式:XXX.XXX.XXX-XX if (cleanText.Length > 0) { formattedText = cleanText.Substring(0, 1); if (cleanText.Length >= 3) formattedText = $"{cleanText.Substring(0, 3)}."; if (cleanText.Length >= 6) formattedText += $"{cleanText.Substring(3, 3)}."; if (cleanText.Length >= 9) formattedText += $"{cleanText.Substring(6, 3)}-"; if (cleanText.Length >= 11) formattedText += cleanText.Substring(9, 2); } // 避免循环触发TextChanged if (textField.Text != formattedText) { textField.Text = formattedText; // 光标定位到末尾 textField.CursorPosition = formattedText.Length; } } }
在XAML中引用该Behavior:
<material:TextField x:Name="txtCpf" Title="CPF" FontFamily="MontserratMedium" TitleColor="#902E2E2E"> <material:TextField.Behaviors> <local:CpfMaskBehavior /> </material:TextField.Behaviors> </material:TextField>
(注:local是自定义Behavior所在的命名空间,需在XAML根节点添加声明,例如xmlns:local="clr-namespace:你的应用命名空间")
方案二:直接在TextChanged事件中处理
如果不想自定义Behavior,可直接在已有的txtCpf_TextChanged事件中实现格式化逻辑:
private void txtCpf_TextChanged(object sender, TextChangedEventArgs e) { if (sender is not TextField textField) return; var cleanText = Regex.Replace(e.NewTextValue ?? string.Empty, @"[^\d]", ""); var formattedText = string.Empty; if (cleanText.Length > 0) { formattedText = cleanText.Substring(0, 1); if (cleanText.Length >= 3) formattedText = $"{cleanText.Substring(0, 3)}."; if (cleanText.Length >= 6) formattedText += $"{cleanText.Substring(3, 3)}."; if (cleanText.Length >= 9) formattedText += $"{cleanText.Substring(6, 3)}-"; if (cleanText.Length >= 11) formattedText += cleanText.Substring(9, 2); } if (textField.Text != formattedText) { textField.Text = formattedText; textField.CursorPosition = formattedText.Length; } }
同时记得移除之前无效的MaskedBehavior,避免逻辑冲突。
注意事项
- 两种方案都会自动过滤非数字输入,确保用户只能输入数字
- 光标会自动定位到输入末尾,提升输入流畅度
- 若需额外的CPF合法性校验,可在格式化完成后添加对应校验逻辑
内容的提问来源于stack exchange,提问作者Reanii
相关产品推荐
相关产品推荐

