解决.NET MAUI数字输入框的Format Exception异常问题
.NET MAUI Entry空值绑定异常问题
场景复现
我在.NET MAUI应用中使用了如下配置的Entry控件:
<Entry Text="{Binding EntryInput}" Placeholder="{Binding PlaceholderString}" Keyboard="{Binding KeyboardSetting}" Margin="5, 0, 5, 15" x:Name="entryControl"/>
根据输入类型,我会将KeyboardSetting设为Numeric或默认值。对应的可绑定属性定义如下:
public static readonly BindableProperty EntryInputProperty = BindableProperty.Create(nameof(EntryInput), typeof(string), typeof(MyInputView), default(string), BindingMode.TwoWay); ... public string EntryInput { get => (string)GetValue(EntryInputProperty); set => SetValue(EntryInputProperty, value); }
我希望视图加载时将Entry文本清空为string.Empty(即使是数字输入框也不设默认值“0”),但使用Numeric键盘时会抛出**System.FormatException: 'The input string '' was not in a correct format.'**异常。用户删除Entry中所有文本时也会触发此异常,还导致UI加载缓慢。
异常堆栈信息
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, ReadOnlySpan`1 value, TypeCode type) at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info) at System.Double.Parse(String s, IFormatProvider provider) at System.Convert.ToDouble(String value, IFormatProvider provider) at System.String.System.IConvertible.ToDouble(IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at Microsoft.Maui.Controls.BindingExpression.TryConvert(Object& value, BindableProperty targetProperty, Type convertTo, Boolean toTarget) in D:\a\_work\1\s\src\Controls\src\Core\BindingExpression.cs:line 464
解决方案
1. 自定义绑定转换器处理空值
编写转换器拦截空字符串的转换逻辑,避免触发格式异常:
public class NumericStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // 从ViewModel向Entry转换,空值直接返回string.Empty return value?.ToString() ?? string.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { // 从Entry向ViewModel转换,空值直接返回string.Empty var input = value as string; return string.IsNullOrEmpty(input) ? string.Empty : input; } }
在XAML中引用并使用转换器:
<ContentPage.Resources> <local:NumericStringConverter x:Key="NumericStringConverter"/> </ContentPage.Resources> <Entry Text="{Binding EntryInput, Converter={StaticResource NumericStringConverter}}" Placeholder="{Binding PlaceholderString}" Keyboard="{Binding KeyboardSetting}" Margin="5, 0, 5, 15" x:Name="entryControl"/>
2. 调整可绑定属性配置
修改可绑定属性的默认值并添加验证逻辑,确保空值合法:
public static readonly BindableProperty EntryInputProperty = BindableProperty.Create( nameof(EntryInput), typeof(string), typeof(MyInputView), string.Empty, // 将默认值设为string.Empty而非null BindingMode.TwoWay, validateValue: (bindable, value) => { // 允许空字符串或合法数字格式的字符串 var strValue = value as string; return string.IsNullOrEmpty(strValue) || double.TryParse(strValue, out _); });
3. 拦截Entry文本变更事件
在代码后台手动处理空值场景,跳过绑定的自动转换逻辑:
entryControl.TextChanged += (sender, e) => { if (string.IsNullOrEmpty(e.NewTextValue) && entryControl.Keyboard == Keyboard.Numeric) { var viewModel = BindingContext as MyInputViewModel; viewModel?.EntryInput = string.Empty; // 锁定UI文本,避免循环触发更新 entryControl.Text = string.Empty; } };
4. 优化UI加载性能
- 视图加载时先设置
KeyboardSetting为默认值,再设置EntryInput为string.Empty,最后切换到Numeric键盘,减少绑定触发次数 - 确保ViewModel的
INotifyPropertyChanged只在值真正变化时触发,避免不必要的UI更新 - 简化绑定转换逻辑,避免在转换器中执行复杂操作
内容的提问来源于stack exchange,提问作者OXO
相关产品推荐
相关产品推荐

