Reader small image

You're reading from  The MVVM Pattern in .NET MAUI

Product typeBook
Published inNov 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781805125006
Edition1st Edition
Languages
Right arrow
Author (1)
Pieter Nijs
Pieter Nijs
author image
Pieter Nijs

Pieter Nijs is a .NET consultant at Xebia in Belgium, with a keen interest in mobile and cloud development. He's been instrumental in diverse projects, from vast healthcare and telecom systems to compact LOB apps. Now, Pieter's exploring AI's potential to enhance customer projects innovatively. Passionate about technology, he actively experiments and shares knowledge as a conference speaker and trainer. Pieter has been awarded the Microsoft MVP Award since 2017, reflecting his unwavering passion and expertise in serving the community.
Read more about Pieter Nijs

Right arrow

Localization with MVVM

So, we’ve built this fantastic Recipes! app, and we’re quite pleased with its design and features. However, as it stands, the app is entirely in English. What about culinary enthusiasts from different parts of the world? The answer is localization, specifically focusing on translating all aspects of our app to make it accessible and user-friendly to a global audience.

In this chapter, we’ll tackle localization through the lens of MVVM. We’ll be looking at translating the hardcoded copy labels that are baked into the app, but also at effectively fetching language-specific data from the API. To accomplish this, we’ll delve into the following topics:

  • Working with cultures, resource files, and localization
  • Looking at a localization solution for MVVM
  • Using a custom Translate markup extension
  • Fetching localized data from APIs

As we dive into this chapter, remember that our journey through localization...

Technical requirements

As always, for hands-on experience and to keep pace with the content, head over to our GitHub repository at https://github.com/PacktPublishing/MVVM-pattern-.NET-MAUI/tree/main/Chapter12. Begin with the code in the Start folder, and, for a comprehensive view, you can always refer to the Finish folder, which houses the polished, end-of-chapter code.

Working with cultures, resource files, and localization

Before we jump into the actual coding bits and look at how we can integrate localization in MVVM, let’s make sure we’re all on the same page about what we mean by culture in the .NET MAUI context. Culture, in this case, refers to the settings that determine the language to be used and the display format for items such as dates, times, currency, and so on.

Let’s start with how to retrieve the user’s culture in .NET MAUI.

Getting the user’s culture

The CultureInfo class is part of the System.Globalization namespace in .NET and serves as a central point for obtaining culture-specific information, such as language, country, date formats, number formats, and more. It also contains CurrentCulture and CurrentUICulture properties that can be used to get or set the user’s current culture and “UI culture.”

CurrentCulture versus CurrentUICulture

CurrentCulture defines...

Looking at a localization solution for MVVM

In this section, we’ll look at a solution that’s not just functional but also fits well with the MVVM architectural pattern. Whether you need to localize text within your ViewModels or dynamically update language in your UI, this approach has you covered. It’s a solution that I’ve personally implemented in numerous projects over the years. While I’ve made some refinements along the way, the core concept has stood the test of time and proven its effectiveness in real-world applications.

Warning – culture settings are thread-specific

When allowing the user to switch cultures inside the app, we should be wary of the fact that when updating CultureInfo inside async operations, those changes will not automatically propagate to the parent thread. A localization strategy needs to be designed with this in mind to avoid inconsistencies.

In the code accompanying this chapter, two new projects have...

Using a custom Translate markup extension

We previously set up a localization solution for our app. While it works effectively, the data-binding statements were a bit verbose and would have to be repeated for each string. Building on that foundation, in this section, we’ll introduce a streamlined approach: a custom markup extension designed specifically for translations.

But before we proceed, let’s briefly revisit what markup extensions are. Markup extensions provide a way to compute or retrieve property values at runtime rather than just setting them to static values. This functionality makes them particularly handy for tasks such as resource lookups, data binding, or, in our case, simplifying translation retrieval.

It’s important to note that we’re not changing how we leverage data binding to bind to our resources. Instead, we’re just making the XAML code easier to write and read. The actual data-binding process stays the same. This is essentially...

Fetching localized data from APIs

Before we wrap up this chapter, let’s have a quick look at how we could pass the user’s language to the API so that it can return localized data. One approach is to include a language parameter in every service and repository method, allowing the ViewModel to pass the user’s current language. However, I believe adding such parameters can clutter the code. A cleaner alternative is to handle this within the repositories. Let’s see how:

  1. First, let’s update the IRecipeAPI interface by adding a language parameter of type string to the GetRecipes method. The following snippet shows how we can configure Refit to pass this additional parameter as an Accept-Language request header when executing the API call:
    Task<ApiResponse<RecipeOverviewItemsDto>>
      GetRecipes([Header("Accept-Language")] string
        language, int pageSize = 7, int pageIndex = 0);

    We could pass this...

Summary

We kicked off this chapter with an introduction to localization, understanding its importance in ensuring our app resonates with users globally. Before diving deep, we explored the basics of how localizable values can be statically bound, offering a foundational approach.

Building on this, we introduced a more dynamic localization framework. This allowed for more flexible updates and interactions. Following this, we delved into simplifying our XAML through the Translate markup extension. While it made our data-binding statements sleeker, the underlying mechanism remained unchanged.

Next, we discussed getting localized data from our APIs. We found a neat way to tell the API about the user’s language choice without making our code messy. By using the ILocalizationManager, we kept our approach consistent. And, with Messaging, our app knows when to fetch new data if a user changes their language.

The big takeaway? All our steps respected the key MVVM idea of “...

Further reading

To learn more about the topics that were covered in this chapter, take a look at the following resources:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
The MVVM Pattern in .NET MAUI
Published in: Nov 2023Publisher: PacktISBN-13: 9781805125006
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Pieter Nijs

Pieter Nijs is a .NET consultant at Xebia in Belgium, with a keen interest in mobile and cloud development. He's been instrumental in diverse projects, from vast healthcare and telecom systems to compact LOB apps. Now, Pieter's exploring AI's potential to enhance customer projects innovatively. Passionate about technology, he actively experiments and shares knowledge as a conference speaker and trainer. Pieter has been awarded the Microsoft MVP Award since 2017, reflecting his unwavering passion and expertise in serving the community.
Read more about Pieter Nijs