可以爲int綁定條目但是你不能綁定一個可爲空的int。您可以添加該號碼轉換爲字符串另一個屬性,或者你可以很容易地創建一個值轉換器這樣的...
class NullableIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var nullable = value as int?;
var result = string.Empty;
if (nullable.HasValue)
{
result = nullable.Value.ToString();
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var stringValue = value as string;
int intValue;
int? result = null;
if (int.TryParse(stringValue, out intValue))
{
result = new Nullable<int>(intValue);
}
return result;
}
...在你的頁面像這樣使用它...
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:IntBinding"
x:Class="IntBinding.DemoPage">
<ContentPage.Resources>
<ResourceDictionary>
<local:NullableIntConverter x:Key="NullableIntConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout>
<Entry Text="{Binding Number, Mode=TwoWay, Converter={StaticResource NullableIntConverter}}" Placeholder="Number" Keyboard="Numeric" />
<Label Text="{Binding Number, Converter={StaticResource NullableIntConverter}}" />
</StackLayout>
</ContentPage>
綁定系統包含了一些明顯的類型轉換,但字符串的Int32?不是其中之一 –