2017-03-09 65 views
4

我在Xamarin形式簡單的條目:條目綁定到int?在Xamarin窗體

<Entry Text="{Binding Number, Mode=TwoWay}" Placeholder="Number" Keyboard="Numeric" /> 

在視圖模型有屬性:

private int? _number; 
    public int? Number 
    { 
     get { return _number; } 
     set 
     { 
      if (SetProperty(ref _number, value)) 
      { 
       OnPropertyChange(nameof(Number)); 
      } 
     } 
    } 

我在進入和按鍵輸入數字,但在按鈕按下的過程 - 數仍然是空的。我究竟做錯了什麼?

+0

綁定系統包含了一些明顯的類型轉換,但字符串的Int32?不是其中之一 –

回答

6

輸入接受一個字符串。如果你想一個int屬性綁定你應該使用IValueConverter,但我認爲最好的辦法是使用String屬性不是從字符串值轉換爲INT

public string StrNumber{ 
    get { 
     if (Number == null) 
      return ""; 
     else 
      return Number.ToString(); 
    } 

    set { 
     try { 
      Number = int.Parse(value); 
     } 
     catch{ 
      Number = null; 
     } 
    } 
} 
8

可以爲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>