MVVM Cross with Xamarin.Platform – Resx localization

Short introduction

Nowadays everyone who wants to reach global markets with mobile application has to provide localization – support for more than one language. This is why I decided to write this article to help Xamarin developers with implementation of such feature in the app. I am using Xamarin.Platform approach and Mvvm Cross framework.

What do I need to start?

  1. Visual Studio 2017 Community (for free or choose higher version) or Visual Studio for MAC
  2. Mvvm Cross framework installed in solution projects (you can find Mvvm Cross – jump start on my GitHub here )

Let’s start

If you already have Xamarin.Platform project with Mvvm Cross installed we can start working on localization support. We will use .resx files to store strings for different languages – in our case English and German.

Add .resx files to support English and German string resources

In .Core project (PCL) add folder called “Localization”. Then right click on it and add first .resx file – call it “AppResources”:

As you can see two files were generated by Visual Studio: “AppResources.resx” and “AppResources.Designer.cs”. Second file contains C# code which enables access to string resources contained in .resx file using ResourceManager.

Update nameof first file: “AppResources.de.resx” and remove “AppResources.Designer.cs” file. No worries. This approach enables us to add second .resx file – at the time of writing this post there was a bug in Visual Studio 4 Mac and I was not able to type full name (“AppResources.de”) in wizard’s “Name” field.

Now add one more .resx file with name: “AppResources”. Final structure should look like below:

As you can see we need only one “AppResources.Designer.cs” file. Rest of .resx files (like “AppResources.de.resx”) do not need it because they will be handled by ResourceManager globally. You can read more about this process here.

Additionally if you would like provide support for more languages check table of language culture names here.

Add some string resources to .resx files

Once we have two .resx files we can add some string resources to it. Open “AppResources.resx” file first. It should look like below:


	
		text/microsoft-resx
	
	
		2.0
	
	
		System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	
	
		System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	

      
 Welcome to Xamarin Platform application!
 
    

As you can see at the bottom I added new “data” entry. “name” tag is unique name of string resource with following convention: “NameOfViewModelWhereStringResourceIsUsed.StringResourceName”. This convention is supported by “MvvmCross.Plugin.ResxLocalization” plugin which we will apply soon.

You can see that inside “data” tag I added some text – “Welcome to Xamarin Platform application”. Of course you can add more resources if you wish.

Now open “AppResources.de.resx” file. It should look like below:


	
		text/microsoft-resx
	
	
		2.0
	
	
		System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	
	
		System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
	

   
 Willkommen bei Xamarin Platform Applikation!
 
    

As you can see I have string resource called “MainViewModel.WelcomeText” (exactly the same name like in previous file) but text between “data” tag is written in German.

Great, .resx files are ready. Please note that we keep them in .Core project which is shared between applications so I do not have to duplicate anything per project.

Add MvvmCross.Plugin.ResxLocalization NuGet package to .Core project (PCL)

Now we can use great plugin provided by Mvvm Cross called ResxLocalization. If you want to read more about it click here.

Right click on “packages” folder and search for “MvvmCross.Plugin.ResxLocalization”:

Now open class which derives from “MvxApplication” – in my case this is “AppSetup.cs” file located in “Configuration/ApplicationSetup” folder.

In overrided method called “Initialize” add below line of code:

Mvx.RegisterSingleton(new MvxResxTextProvider(AppResources.ResourceManager));

We need to register “MvxResxTextProvider” in IoC container with our string resources manager (as you can see I passed “AppResources.ResourceManager”) to have access to all localized strings.

Now in base class for each ViewModel in my application (called “ApplicationMvxViewModel” and located in “ViewModels/Base” folder) we have to add below property to have access to localized string resources from ViewModels and Views bound to them:

public IMvxLanguageBinder TextSource => new MvxLanguageBinder("", GetType().Name);

Access localized string resources in Xamarin.iOS and Xamarin.Android apps

For Xamarin.iOS project we will handle localization through ViewController file. In my case this is “MainViewController”. In my “MainViewController” I have method called “SetupBinding” which is invoked when View is ready:

private void SetupBindings()
	{
            var bindingSet = this.CreateBindingSet();

            bindingSet.Bind(_welcomeTextLabel).To(ViewModel => ViewModel.TextSource)
                      .WithConversion(new MvxLanguageConverter(), "WelcomeText");

            bindingSet.Apply();
	}

As you can see I am creating binding set for “_welcomeTextLabel” control and “ViewModel.TextSource” property with conversion where I passed name of string resource: “WelcomeText”. It means that my label will display welcome text from .resx file depending on the mobile device language preferences.

For Xamarin.Android we can handle localization in .axml designer files. In my case this is “main_activity.axml” file.

I added TextView control:

As you can see I am using “MvxLang” tag provided by Mvvm Cross. With this tag I can type which string resource should be displayed in TextView – in this case “WelcomeText” from .resx file.

To be able to use “MvxLang” tag we should also override “FillValueConverters” method in “Setup.cs” file located in “Configuration” folder:

protected override void FillValueConverters(MvvmCross.Platform.Converters.IMvxValueConverterRegistry registry)
{
      base.FillValueConverters(registry);
      registry.AddOrOverwrite("Language", new MvxLanguageConverter());
}

That’s it!

Sum up

Localization with Mvvm Cross is not so complicated as you can think (of course with clear information and instructions). Now you now how to provide support for localization in your Xamarin.iOS and Xamarin.Android applications.

I strongly recommend to visit my GitHub page where you can find ready-to-go sample described in this article. It is available here.

Have fun!

您可能感兴趣的

Not Hotdog: Android Things and Visual Studio/Xamar... Meeting Information: Not Hotdog: Android Things and Visual Studio/Xamarin We will cover the new platform announced by Google, called Android Thing...
Adding Badge to ToolbarItem in Xamarin Forms There are some use cases when we need to add a badge to a toolbar item to show a dynamic counter. An example of this might be when having a shopping c...
Xamarin.Tip – Mvvm Light and Dependency Injection... Inversion of Control and Dependency Injection are some design principles that help make our applications more flexible and scalable. They both help...
Xamarin: Performing Geospatial Calculations with A... Azure CosmosDB is a multi-model, globally distributed database, as well as a geospatial calculation powerhouse. It can calculate the distance between ...
深入浅出 MVVM 教程应用篇(三):Cache 简介 背景 这几年 MVP 架构在安卓界非常流行,几乎已经成为主流框架,它让业务逻辑 和 UI操作相对独立,使得代码结构更清晰。 MVVM 在前端火得一塌糊涂,而在安卓这边却基本没见到几个人在用,看到介绍 MVVM 也最多是讲 DataBinding 或 介绍思想的。偶尔看到...
责编内容来自:Mobile programmer (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » MVVM Cross with Xamarin.Platform – Resx localization



专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录