Aaron Bratcher
Aaron Bratcher

Reputation: 6451

Cross-platform image name?

I have some xaml markup to specify the image file based on a binding.

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

My model class has this to return the file name:

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

This works great for iOS because the files are named check.png, [email protected], etc. and my images are showing. However images aren't showing on Android because I need to specify "check.png" or "card.png". How can I make this work for Android too while keeping this a strictly model class?

Upvotes: 0

Views: 702

Answers (2)

Gerald Versluis
Gerald Versluis

Reputation: 33993

Check out the documentation here.

Easiest would be to use the compiler directive like this:

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

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

But there probably are more elegant solutions.

Upvotes: 1

dbr
dbr

Reputation: 61

This could be achieved using a Value Converter:

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();
        }
    }
}

Then setup any desired pages to access the new ImageSourceConverter:

<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"
         ...>

Specify the converter as a page resource so it can be used in the binding:

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

Finally, update any image Source bindings to use the converter:

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

Upvotes: 3

Related Questions