Accueil

Localisation XAML Markup Extension

Tutoriel Xamarin

Posté par Véronique le 11 October 2017

Dans un projet Xamarin Forms, il est possible de créer ses vues en utilisant XAML. Pour afficher les traductions à partir de ce code, il faudra faire appel à une classe utilitaire que nous allons créer.

(Plus d'infos sur developer.xamarin.com)


Créer les fichiers de ressources

Créer un dossier Localization, puis ajouter un fichier de ressources AppResources.resx.

Créer une classe utilitaire

Dans le dossier Utils, créer une classe TranslateExtension qui implémente IMarkupExtension.

Cela permet d’étendre les propriétés Text, afin de pouvoir y fournir une clé de traduction et la traduire à l'exécution.

[ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension
{
    private static readonly Lazy<ResourceManager> ResMgr =
        new Lazy<ResourceManager>(() => new ResourceManager("Project.Localization.AppResources", typeof(TranslateExtension).GetTypeInfo().Assembly));

    public string Text { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Text == null)
            return "";

        var translation = ResMgr.Value.GetString(Text);

        if (translation == null)
        {
#if DEBUG
            throw new ArgumentException(String.Format("Key '{0}' was not found in resources ", Text), "Text");
#else
            translation = Text; // returns the key, which GETS DISPLAYED TO THE USER
#endif
        }

        return translation;
    }
}

Utiliser la fonction Translate pour accéder aux ressources

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:i18n="clr-namespace:Project.Utils"
             x:Class="Project.Views.HomePage"
             Title="{i18n:Translate Menu_Home}">