Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
This repository was archived by the owner on Nov 12, 2023. It is now read-only.
/I18N-PortablePublic archive

Simple and cross platform internationalization/translations for Xamarin and .NET

License

NotificationsYou must be signed in to change notification settings

xleon/I18N-Portable

Repository files navigation

This project is now archived as there are no plans to update it.Please consider it before using it.

Simple and cross platform internationalization/translations for Xamarin and .NET

NuGetNuGetAppVeyorCodecov

  • Cross platform
  • Simple to use:"key".Translate().
  • Simple and fluent initialization setup.
  • Readable locale files (.txt with key/value pairs).
  • Support for custom file formats (json, xml, etc)
  • Light weight
  • No dependencies.
  • Well tested

https://cloud.githubusercontent.com/assets/145087/24824462/c5a0ecce-1c0b-11e7-84d3-4f0fa815c9da.png

Install

Install it on your PCL and platform projects.From nuget package manager console:

PM> Install-Package I18NPortable

Setup locales

  • In your PCL/Core project, create a directory called "Locales".
  • Create a{languageCode}.txt file for each language you want to support.languageCode can be a two letter ISO code or a culture name like "en-US". Seefull list here.
  • Set "Build Action" to "Embedded Resource" on the properties of each file

Locale content sample

# key = value (the key will be the same across locales)one = unotwo = dosthree = tres four = cuatrofive = cinco  # Enums are supportedAnimals.Dog = PerroAnimals.Cat = GatoAnimals.Rat = RataAnimals.Tiger = TigreAnimals.Monkey = Mono # Support for string.Format()stars.count = Tienes {0} estrellas TextWithLineBreakCharacters = Line One\nLine Two\r\nLine Three Multiline = Line One    Line Two    Line Three

Other file formats (including custom) supported

Fluent initialization

I18N.Current.SetNotFoundSymbol("$")// Optional: when a key is not found, it will appear as $key$ (defaults to "$").SetFallbackLocale("en")// Optional but recommended: locale to load in case the system locale is not supported.SetThrowWhenKeyNotFound(true)// Optional: Throw an exception when keys are not found (recommended only for debugging).SetLogger(text=>Debug.WriteLine(text))// action to output traces.SetResourcesFolder("OtherLocales")// Optional: The directory containing the resource files (defaults to "Locales").Init(GetType().GetTypeInfo().Assembly);// assembly where locales live

Usage

stringone="one".Translate();stringnotification="Mailbox.Notification".Translate("Diego",3);// same as string.Format(params). Output: Hello Diego, you've got 3 emailsstringmissingKey="missing".Translate();// if the key is not found the output will be $key$. Output: $missing$stringgiveMeNull="missing".TranslateOrNull();// Output: nullstringdog=Animals.Dog.Translate();// translate enum value (Animals is an Enum backed up in the locale file with "Animals.Dog = Perro")List<string>animals=I18N.Current.TranslateEnumToList<Animals>();List<Tuple<Animals,string>>animals=I18N.Current.TranslateEnumToTupleList<Animals>();stringdog=animals[0].Item2;// PerroDictionary<Animals,string>animals=I18N.Current.TranslateEnumToDictionary<Animals>();stringdog=animals[Animals.Dog];// Perro// List of supported languages (present in the "Locales" folder) in case you need to show a picker listList<PortableLanguage>languages=I18N.Current.Languages;// Each `PortableLanguage` has 2 strings: Locale and DisplayName// change language on runtimeI18N.Current.Language=language;// instance of PortableLanguage// change language on runtime (option 2)I18N.Current.Locale="fr";

Data binding

I18N implementsINotifyPropertyChanged and it has an indexer to translate keys. For instance, you could translate a key like:

string three = I18N.Current["three"];

With that said, the easiest way to bind your views toI18N translations is to use the built-in indexerby creating a proxy object in your ViewModel:

publicabstractclassBaseViewModel{publicII18NStrings=>I18N.Current;}

Xaml sample

<ButtonContent="{Binding Strings[key]}" />

Xamarin.Forms sample

<ButtonText="{Binding Strings[key]}" />`

Android/MvvmCross sample

<TextViewlocal:MvxBind="Text Strings[key]" />

iOS/MvvmCross sample

varset=this.CreateBindingSet<YourView,YourViewModel>();set.Bind(anyUIText).To("Strings[key]");

Supported formats

The library ships with a single format reader/parser that isTextKvpReader. Any other reader will be isolated in a different nuget/plugin to keep the library as simple as possible.

ReaderFormatSource
TextKvpReaderSee sampleI18NPortable
JsonKvpReaderSee sampleI18NPortable.JsonReaderI18NPortable.JsonReader
JsonListReaderSee sampleI18NPortable.JsonReaderI18NPortable.JsonReader

To use any non-default format, it needs to be added on initialization:

I18N.Current.AddLocaleReader(newJsonKvpReader(),".json")// ILocaleReader, file extension// add more readers here if you need to.Init(GetType().Assembly);

Creating a custom reader for another file format:

It's very easy to create custom readers/parsers for any file format you wish.For instance, lets take a loot at the above mentionedJsonKvpReader:

Given thisen.json file

{"one":"uno","two":"dos","three":"tres"}

Creating a custom reader is as simple as implementingILocaleReader:

publicinterfaceILocaleReader{Dictionary<string,string>Read(Streamstream);}
publicclassJsonKvpReader:ILocaleReader{publicDictionary<string,string>Read(Streamstream){using(varstreamReader=newStreamReader(stream)){varjson=streamReader.ReadToEnd();returnJsonConvert.DeserializeObject<Dictionary<string,string>>(json).ToDictionary(x=>x.Key.Trim(), x=>x.Value.Trim().UnescapeLineBreaks());}}}

Contributing new readers

If you implemented a new reader for another file format and you want to contribute, feel free to make a pull request. Any new reader will live in their own project in the solution and will produce a different nuget as a plugin to I18NPortable.

About

Simple and cross platform internationalization/translations for Xamarin and .NET

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp