Issue
I have a Xamarin Forms application with a language selector that will be exposed to customers. When I switch language, I call a SetLocale() method to switch the current language.
public static void SetLocale(CultureInfo culture)
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
AppResources.Culture = culture;
}
All textes are updated well (they come from resx files) but the images remains the one from the default application language (selected in the application settings) that I defined in the info.plist.
I putted my images in the iOS project in Resources/.lproj following the xamarin documentation
I bind them in the xaml file as usually
<Image Source="{Binding Image}"></Image>
How can I do to make the translation work for the images as well?
Solution
After many research, I couldn't find a way to do it with the native bundle of iOS.
I ended up by doing a markup extension following this tutorial and I customized it to have a fallback to a default locale if the image does not exists.
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinTest.Custom
{
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
return null;
var resourceName = string.Format("XamarinTest.Images.{0}.{1}", CultureInfo.CurrentUICulture.Name.Replace('-', '_'), Source);
if (ResourceExists(resourceName))
return ImageSource.FromResource(resourceName, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
return ImageSource.FromResource(string.Format("XamarinTest.Images.default.{0}", Source), typeof(ImageResourceExtension).GetTypeInfo().Assembly);
}
private string[] resourceNames;
private bool ResourceExists(string resourceName)
{
if (resourceNames == null)
{
resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
}
return resourceNames.Contains(resourceName);
}
}
}
I set the build action to EmbeddedResource for every images
Then in a view, I just add
xmlns:l="clr-namespace:XamarinTest.Custom"
...
<Image Source="{l:ImageResource qr.png}"
HeightRequest="160"
WidthRequest="160"></Image>
Answered By - Demonia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.