Created
February 21, 2018 22:18
-
-
Save matthewrdev/8b8c38948a59b414cb34930a133e0e56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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