Skip to content

Instantly share code, notes, and snippets.

@matthewrdev
Created February 21, 2018 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewrdev/8b8c38948a59b414cb34930a133e0e56 to your computer and use it in GitHub Desktop.
Save matthewrdev/8b8c38948a59b414cb34930a133e0e56 to your computer and use it in GitHub Desktop.
using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Xamarin.Forms.Xaml;
using Xamarin.Forms;
namespace MyApp.il8n
{
// You exclude the 'Extension' suffix when using in Xaml markup
[ContentProperty ("Text")]
public class TranslateExtension : IMarkupExtension
{
readonly CultureInfo ci;
const string ResourceId = "MyApp.Resources.Resources";
private static readonly Lazy<ResourceManager> ResMgr = new Lazy<ResourceManager>(()=> new ResourceManager(ResourceId, typeof(TranslateExtension).GetTypeInfo().Assembly));
public TranslateExtension()
{
if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
{
ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
}
}
public string Text { get; set; }
public object ProvideValue (IServiceProvider serviceProvider)
{
if (Text == null)
return "";
var translation = ResMgr.Value.GetString(Text, ci);
if (translation == null)
{
#if DEBUG
throw new ArgumentException(
String.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.", Text, ResourceId, ci.Name),
"Text");
#else
translation = Text; // returns the key, which GETS DISPLAYED TO THE USER
#endif
}
return translation;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment