Reader small image

You're reading from  .NET MAUI Cross-Platform Application Development - Second Edition

Product typeBook
Published inMar 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781835080597
Edition2nd Edition
Languages
Right arrow
Author (1)
Roger Ye
Roger Ye
author image
Roger Ye

Roger Ye is an embedded system programmer who has great interest in virtualization, Android, and cross-platform technologies. His professional experience includes working with major companies like Motorola, Emerson, Intel, and EPAM, where he held the position of Engineering Manager. At Motorola and Emerson, he worked on embedded system projects for mobile devices and telecommunication infrastructures. He is now an engineering manager at EPAM, working with a team to deliver digital solutions for diverse clients.
Read more about Roger Ye

Right arrow

Exploring MVVM and Data Binding

In the previous chapter, we explored how to construct user interfaces (UIs) using XAML. In this chapter, we will dive into the Model-View-View-Model (MVVM) pattern and data binding. The MVVM pattern, a widely adopted architectural pattern, is key in creating maintainable, scalable, and testable applications. In the context of .NET MAUI, MVVM separates the user interface logic, data, and the app’s structure into three distinct components: Model, View, and ViewModel. This separation leads to a clean and organized codebase, making it easier to develop and maintain the application. Data binding is a technique that connects the view (UI) with the ViewModel in a way that the UI reflects the ViewModel’s data and changes synchronously and automatically.

In this chapter, our initial focus will be on introducing MVVM and data binding. For a better design and cleaner code, we will employ the MVVM Toolkit, part of the .NET Community Toolkit. The...

Technical requirements

To test and debug the source code in this chapter, you need to have Visual Studio 2022 installed on your PC or Mac. Please refer to the Development environment setup section in Chapter 1, Getting Started with .NET MAUI, for the details.

The source code for this chapter is available in the following GitHub repository: https://github.com/PacktPublishing/.NET-MAUI-Cross-Platform-Application-Development-Second-edition/tree/2nd/chapter04.

To check out the source code of this chapter, we can use the following command:

$ git clone -b 2nd/chapter04 https://github.com/PacktPublishing/.NET-MAUI-Cross-Platform-Application-Development-Second-edition.git PassXYZ.Vault2

To find out more about the source code in this book, please refer to the Managing the source code in this book section in Chapter 2, Building Our First .NET MAUI App.

Understanding MVVM and MVC

In software design, we usually follow and reuse good practices and design patterns. The Model-View-Controller (MVC) pattern is an approach to decoupling the responsibilities of a system. It can help to separate the implementation of the UI and the business logic into different parts.

Figure 4.1: The MVC pattern

Figure 4.1: The MVC pattern

The MVC pattern, as shown in Figure 4.1, divides the responsibilities of the system into three distinct parts:

  • Model: The model represents the data and the business logic of the application. It is responsible for storing the app’s data, handling data validation, and performing any necessary data processing. Model classes typically interact with data sources, such as databases, web APIs, or file storage, to fetch and store data. Model classes usually can be implemented as Plain Old CLR Objects (POCOs) or Data Transfer Objects (DTOs). POCO is a class that doesn’t depend on any framework-specific classes, so POCO...

Data binding

Let’s explore how MVVM and data binding works. We can use an item detail page implementation in our app to analyze how data binding works. The following list includes the view, ViewModel, and model that we are going to explore:

  • View: ItemDetailPage, see Listing 3.4 in the previous chapter
  • ViewModel: ItemDetailViewModel, see Listing 4.1
  • Model: Item (access through the IDataStore interface), see Listing 3.3 in the previous chapter

ItemDetailPage is a view used to display the content of an instance of Item. The data is retrieved from the ViewModel. The UI elements presenting the content of Item are connected to the ViewModel instance through data binding.

A diagram of a binding object  Description automatically generated

Figure 4.4: Data binding

As we can see in Figure 4.4, data binding is used to synchronize the properties of target and source objects. There are three objects involved in data binding and they are the binding target, binding source, and binding object.

Binding object...

.NET Community Toolkit

In this section, we will use the MVVM Toolkit to refactor our ViewModel code. The MVVM Toolkit is a module within the .NET Community Toolkit, specifically designed for building applications following the MVVM design pattern.

The .NET Community Toolkit (formerly Windows Community Toolkit) is a collection of helper functions, custom controls, and app services designed to simplify and accelerate .NET app development. The toolkit is open source and maintained by the community, offering a suite of tools for various .NET development platforms, such as .NET MAUI, Xamarin, UWP, WPF, and WinUI. The toolkit provides useful components that developers can use out of the box to easily build applications with a rich user interface, common app services, animations, and more.

The MVVM Toolkit supplies a set of base classes, utilities, and attributes that make implementing the MVVM pattern in your .NET applications more efficient and straightforward. The MVVM Toolkit...

Improving the data model and service

After introducing the MVVM pattern, data binding, and the MVVM Toolkit, we have the fundamental knowledge of how to use data binding. In the rest of this chapter, we will explore advanced topics about data binding. We will discuss how to bind to collections first and then we will introduce custom views. Using custom views, we can make XAML code cleaner and more concise.

To examine these topics, a more intricate model layer is required. Instead of creating a hypothetical model layer, we’ll work with the actual model layer in our app, which includes two .NET libraries: KPCLib and PassXYZLib.

To introduce the model layer of our app, let us review the use cases again. We are developing a cross-platform password manager app that is compatible with the popular KeePass database format. We have the following use cases:

  • Use case 1: LoginPage – As a password manager user, I want to log in to the password manager app so that...

Binding to collections

In the previous section, we replaced the model using PassXYZLib. When we introduced data binding, we used ItemDetailPage and ItemDetailViewModel to explain how to bind the source property to the target property.

For the item detail page, we created data binding from one source to one target. However, there are many cases in which we need to bind a data collection to the UI, such as ListView or CollectionView, to display a group of data.

Figure 4.8: Binding to collections

Figure 4.9: Binding to collections

As we can see in Figure 4.9, when we create a data binding from a collection object to a collection view, the ItemsSource property is the one to use. In .NET MAUI, collection views such as ListView and CollectionView can be used, and both have an ItemsSource property.

For the collection object, we can use any collection that implements the IEnumerable interface. However, the changes to the collection object may not be able to update the UI automatically. In order to update...

Using custom views

We implement an instance of ViewCell in DataTemplate in Listing 4.5. This ViewCell is used to display a key-value pair with an icon. The same implementation is employed in both ItemsPage and ItemDetailPage, with the sole distinction being the data binding. We have duplicated code here. To refactor the implementation, we can create a custom view (or custom control).

A custom view in .NET MAUI is a user interface component created by developers to meet custom requirements, provide reusable UI logic, or extend the functionality of existing UI components. Custom views can be built by combining existing controls, deriving from base classes like View, ViewCell, or ContentView, and overriding specific methods to customize rendering or behavior.

To create a custom view that can be reused in both ItemsPage and ItemDetailPage, we should first create a new folder called Templates within the Views directory. In Visual Studio, we can right-click on the Templates folder...

Summary

In this chapter, we learned about the MVVM pattern and applied it to our app development. One key feature of the MVVM pattern is data binding between the view and ViewModel. We delved into data binding and utilized it in the implementation of our app.

To delve deeper into the complexities of data binding, we examined binding to collections and the utilization of data binding in custom views. By employing data binding and custom views, we’re able to refactor XAML code, resulting in a cleaner and more concise codebase.

To demonstrate advanced data binding usage, we need a more intricate model layer. We enhanced the model in this chapter by introducing two packages – KPCLib and PassXYZLib. We replaced the model in the sample code with the models found in these two packages. Subsequently, we updated the UIs of ItemsPage and ItemDetailPage to reflect the changes made to the model.

In the next chapter, we will refine our user stories and continue improving...

Further reading

Learn more on Discord

Join our community’s Discord space for discussions with the author and other readers:

https://packt.link/cross-platform-app

lock icon
The rest of the chapter is locked
You have been reading a chapter from
.NET MAUI Cross-Platform Application Development - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781835080597
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
Roger Ye

Roger Ye is an embedded system programmer who has great interest in virtualization, Android, and cross-platform technologies. His professional experience includes working with major companies like Motorola, Emerson, Intel, and EPAM, where he held the position of Engineering Manager. At Motorola and Emerson, he worked on embedded system projects for mobile devices and telecommunication infrastructures. He is now an engineering manager at EPAM, working with a team to deliver digital solutions for diverse clients.
Read more about Roger Ye