让xamarin的Entry绑定时,支持Nullable类型

xamarin.forms默认情况下,如果属性是double?类型,绑定到Entry上,是无法实现双向绑定的,

可以自定义Converter实现双向绑定

    public class NullableConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ChangeType(value, targetType);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            if( targetType.IsGenericType  )
            {
                Type valueType = targetType.GetGenericArguments()[0];
                object result = System.Convert.ChangeType(value, valueType);
                return Activator.CreateInstance(targetType, result);
            }
            return System.Convert.ChangeType(value, targetType);
        }
    }

然后在app.xaml里面,加入资源配置

    <Application.Resources>
        <ResourceDictionary>
            <local:NullableConverter x:Key="NullableConverter"></local:NullableConverter>
        </ResourceDictionary>
    </Application.Resources>

然后,以后Entry绑定nullable类型时,可以这样写

Text="{Binding propertyName,Converter={StaticResource NullableConverter}}"
原文地址:https://www.cnblogs.com/IWings/p/9993668.html