2015-05-06 51 views
0

我有一些xaml標記來指定基於綁定的圖像文件。跨平臺的圖像名稱?

<Image Grid.Row="0" Grid.Column="3" Source="{Binding ImageSource}" VerticalOptions="Center"/> 

我的模型類有這個返回的文件名:

public string ImageSource { 
    get { 
     return (PaymentType == PaymentType.Check ? "check" : "card"); 
    } 
} 

這個偉大的工程適用於iOS,因爲文件被命名爲check.png,[email protected]等,我的圖片正在展示。不過,Android上沒有顯示圖片,因爲我需要指定「check.png」或「card.png」。我怎樣才能使這個工作的Android也保持這嚴格的模型類?

回答

1

查閱文檔here

最簡單的辦法是使用編譯器指令是這樣的:

public string ImageSource { 
    get { 
     #if __IOS__ 
     return (PaymentType == PaymentType.Check ? "check" : "card"); 
     #endif 

     #if __ANDROID__ 
     return (PaymentType == PaymentType.Check ? "check.png" : "card.png"); 
     #endif 
    } 
} 

但也有可能是更優雅的解決方案。

namespace MyApp.ValueConverters 
{ 
    using System; 
    using System.Globalization; 
    using Xamarin.Forms; 

    public class ImageSourceConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      if (value is string) 
      { 
       switch (Device.OS) 
       { 
        case TargetPlatform.Android: 
         return string.Format("{0}.png", value); 

        default: 
         // No conversion for other platforms 
       } 
      } 
      return value; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 

然後設置任何所需的頁面來訪問新ImageSourceConverter:

+0

我喜歡編譯器指令,所以我將其標記爲正確的答案。 (我真的不希望在頂部使用另一條線)。我設置了一個局部變量來保存沒有.png的fileName,然後使用編譯器指令有條件地追加.png。 –

+0

@AaronBratcher很樂意幫忙!這似乎是現在到達您的解決方案的最快方式,祝您好運! –

3

這可以通過使用值轉換器來實現

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
     xmlns:converters="clr-namespace:MyApp.ValueConverters;assembly=MyApp" 
     ...> 

指定轉換器作爲網頁資源,因此可以使用在綁定:

<ContentPage.Resources> 
    <ResourceDictionary> 
     ... 
     <converters:ImageSourceConverter x:Key="MyImageSourceConverter" /> 
    </ResourceDictionary> 
</ContentPage.Resources> 

最後,更新任何圖像源綁定gs使用轉換器:

<Image Grid.Row="0" Grid.Column="3" VerticalOptions="Center" 
    Source="{Binding ImageSource, Converter={StaticResource MyImageSourceConverter}}" /> 
+0

我更喜歡這個答案,因爲它可以在PCL中工作。 – valdetero