ish1104
ish1104

Reputation: 421

How to Make a app acording to language change

I developed an app that can support two languages. Going beyond that if I need this app for support with many languages. let assume ten languages how to accomplish this requirement

Now what I do is Hard cording it with both languages I used and then retrieve it. If I going to do that for ten languages it does not sound good is there any smart way to do this.

as an example;

I doing with MVVM pattern In my View Model. I use the property and do this its simple way of doing

public string GetPageTitle => AppResources.VitalSignsViewPage_Title;

and my resource file I have two data set if the language has changed it will use write dataset this is what I am doing right now is there any proper smart way to this to many languages.

Upvotes: 0

Views: 47

Answers (1)

Batuhan
Batuhan

Reputation: 1611

There is some solutions to achive this. I recommend to you basic solution ,

Here is an interface for Language Service (It is optionally , if you using Dependency Injection):

public interface ILanguageService
{
    string GetString(string text);
    void ChangeLanguage(bool isALang);
    bool IsALanguage();
}

You can create a service for localization :

namespace Service.Language
{
    public sealed class LanguageService : ILanguageService
    {
        List<LanguageRow> LanguageList;
        private bool IsFirstLang;

        public LanguageService()
        {
            LanguageList = JsonHelper.ReadJSON<List<LanguageRow>>("Service.Language.MultiLanguage.json", typeof(LanguageService));
            IsFirstLang = true;
        }

        public void ChangeLanguage(bool IsFirstLang)
        {
            IsFirstLang =  !IsFirstLang;
        }

        public bool IsALangueage()
        {
            return IsFirstLang;
        }

        public string GetString(string text)
        {
            string result;
            try
            {
                var row = LanguageList.FirstOrDefault(i => i.Code.Equals(text));
                result = IsFirstLang? row.Values[0] : row.Values[1];
            }
            catch
            {
                result = text;
            }
            return result;
        }
    }
}

Here is a model to serialization for json :

public class LanguageRow
{
    public LanguageRow()
    {
        Values = new List<string>();
    }

    public string Code { get; set; }
    public List<string> Values { get; set; }
}

At last, here is json file : (EN-FR)

[
  {
    "Code": "VitalSignsViewPage_Title",
    "Values": [ "Page Title", "Titre de la page" ]
  },
  {
    "Code": "VitalSignsViewPage_SubTitle",
    "Values": [ "Sub Title", "Sous-titre" ]
  },
  {
    "Code": "VitalSignsViewPage_SubSubTitle",
    "Values": [ "Sub Sub Title", "Sous sous-titre" ]
  }
]

You can access translations like :

ILanguageService _langService = new LangService()
_langService.GetString(AppResources.VitalSignsViewPage_Title);

Upvotes: 2

Related Questions