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

Data Binding in .NET MAUI

In the previous chapter, we introduced the fundamentals of data binding in .NET MAUI. Data binding is not only a core feature of .NET MAUI but also a crucial component for effectively building applications using the MVVM design pattern. It creates a robust link between your View and ViewModel, facilitating efficient communication and synchronization between the two.

As we delve deeper into the realm of data binding, it’s essential to grasp some advanced techniques and features. These are the building blocks that empower you to create dynamic user interfaces as efficiently as possible. They allow us to design user interfaces that are not only more interactive but also easier to manage and maintain.

This chapter will cover the following topics:

  • ValueConverters and StringFormat
  • Fallbacks
  • Element and relative binding
  • Multi-bindings
  • Compiled bindings

By the end of this chapter, combined with what we’ve covered...

Technical requirements

Throughout this chapter, we will be adding functionality to the Recipes! app. All the required assets needed to follow along, including all the code used in this chapter, can be found on GitHub at https://github.com/PacktPublishing/MVVM-pattern-.NET-MAUI/tree/main/Chapter04.

ValueConverters and StringFormat

In many cases, the data in your ViewModel doesn’t perfectly match the format expected by the UI. For example, you may have a DateTime object in your ViewModel that you want to display in a specific string format in your View, or an enumeration that should be represented as a more user-friendly string.

This is where ValueConverters and StringFormat come into play. Both of these techniques act as intermediaries, transforming and adapting your ViewModel data into a format suitable for display or interaction in the UI.

In this section, we’ll delve into how to create and use ValueConverters to effectively manage these data transformations, and how formatting can further refine the presentation of your data, ensuring it is meaningful and user-friendly.

Creating and using ValueConverters

A ValueConverter acts as an intermediary between the source (typically the ViewModel) and the target (the View). It provides a way to transform or...

Fallbacks

There are occasions where data binding can fail; the binding source cannot be resolved (yet) or the returned value is null. Although ValueConverters and additional code could tackle many such situations, we can also enhance the resilience of our data bindings by setting fallback values. This can easily be done by setting the TargetNullValue or FallbackValue property in our binding expression.

TargetNullValue

The TargetNullValue property can be used in situations where we want to handle the situation where the resolved binding source target returns null. In other words, the binding engine can resolve the bound property, but this property returns a null value.

In our app, the Calories property on RecipeDetailViewModel is defined as a nullable int. This makes it essential for us to handle any potential null values in our data binding elegantly. If we leave the binding statement as-is, the label would show "Calories: kcal" if the Calories property is null...

Element and relative binding

The versatility of data binding extends beyond linking our Views with ViewModel data. It’s also possible to bind to different elements within our visual tree, opening up many new possibilities.

Both element bindings and relative bindings serve the purpose of allowing bindings to other elements. However, they differ in how they identify the source element:

  • In an element binding, you specify the source element by its name, which is defined by using the x:Name attribute in XAML. The binding refers to this specific named element.
  • In a relative binding, you refer to the source element concerning the position of the current element in the XAML tree. For example, you might bind to a property of the parent element or a property of the next sibling element, or you might even bind to a property of the element itself.

Let’s have a look at both types of binding in more detail. First up: element binding.

Element binding

With...

Multi-bindings

Multi-binding is a powerful feature in XAML data binding that allows you to bind a single target property to multiple source properties and then apply logic to produce one single value. This technique is particularly useful when a target property’s value depends on more than one source property. The simplest example of this is using StringFormat.

Multi-binding StringFormat

A typical multi-binding scenario is where you would like to display multiple values in one label. We could, of course, create a property on the ViewModel that concatenates those values, or we could define this as a Multi-binding with StringFormat.

As an example, we want to show the author of the recipe next to the Last updated timestamp that we already have on our page (Figure 4.9):

Figure 4.9: Showing the author next to the Last updated timestamp

Figure 4.9: Showing the author next to the Last updated timestamp

Here’s how it’s done:

  1. First, let’s add an Author property to our ViewModel:
    public...

Compiled bindings

Compiled bindings are a more performant way of creating bindings and they are verified at compile-time instead of at runtime. Typically, the data binding engine uses reflection to get or set property values on the objects being bound. This approach is flexible and powerful because it allows the binding engine to interact with any object, regardless of its type. However, it also has some performance implications because reflection is slower than direct property access, and it can lead to errors that are only detectable at runtime if a property name is misspelled or if the property doesn’t exist. In contrast, compiled bindings are checked at compile time, which means they can catch errors before the app is even run. Furthermore, because the bindings are compiled into the app, the runtime performance is improved as there’s no need for the binding resolution process that takes place with traditional data binding.

Enabling compiled bindings is pretty simple...

Summary

Data binding is a powerful concept in XAML that makes it easier to separate our view logic from our business logic. It’s a huge enabler for doing MVVM in .NET MAUI. It is a complex subject and it can be challenging to fully master every aspect of it. It involves understanding a variety of concepts and techniques, from simple data bindings to multi-bindings and converters, and from element and relative bindings to high-performance compiled bindings.

However, don’t be overwhelmed. Like any complex subject, understanding data binding comes with time and practice. The more you work with it, the more comfortable you’ll become, and many aspects of it will eventually become second nature.

Remember, the ultimate objective is to efficiently apply the MVVM pattern. In this context, data binding plays a crucial role in connecting your ViewModel’s data and business logic with the UI. The knowledge you’ve gathered in this chapter has brought you...

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