讓xamarin的Entry繫結時,支援Nullable型別
阿新 • • 發佈:2018-11-21
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}}"