The MVVM Pattern in .NET MAUI - Pieter Nijs - E-Book

The MVVM Pattern in .NET MAUI E-Book

Pieter Nijs

0,0
29,99 €

oder
-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In today's fast-paced world of modern software development, teams need to be efficient, productive, and capable of rapidly adapting to changes to deliver high-quality products, making it crucial for developers to write maintainable and easy-to-test code.
The MVVM Pattern in .NET MAUI helps you to thoroughly explore the Model-View-View Model (MVVM) design pattern. The chapters show you how this pattern helps in structuring code to embrace the separation of concerns, allowing for loosely coupled user interface and application logic, which ultimately empowers you to write more robust, maintainable, and testable code. The book also highlights .NET MAUI's capabilities and features, and enables you to delve into the essential components within the framework that facilitate the application of the MVVM pattern. With the help of a sample application, this definitive guide takes a hands-on approach to walk you through both the essential and advanced usages of the MVVM pattern to ensure that you successfully apply the practical aspects of the pattern to your .NET MAUI projects.
By the end of this book, you’ll have gained a comprehensive understanding of the MVVM design pattern and its relevance in the context of .NET MAUI, as well as developed the skills needed to successfully apply it in practice.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



The MVVM Pattern in .NET MAUI

The definitive guide to essential patterns, best practices, and techniques for cross-platform app development

Pieter Nijs

BIRMINGHAM—MUMBAI

The MVVM Pattern in .NET MAUI

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Kunal Sawant

Publishing Product Manager: Akash Sharma

Book Project Manager: Prajakta Naik

Senior Editor: Esha Banerjee

Technical Editor: Maran Fernandes

Copy Editor: Safis Editing

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Nilesh Mohite

Marketing Coordinator: Sonia Chauhan

First published: November 2023

Production reference: 1101123

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-80512-500-6

www.packtpub.com

To my son, Gust, whom I had to disappoint too often while I was working on this book. Now I have time to play, let’s go!

– Pieter Nijs

Foreword

Early in my career as a self-taught software developer, I realized I had a poor grasp of the terms being used by developers around me to describe application architecture. The role and responsibility of a View were obvious to me, but what about a model, presenter, mediator, service, factory, controller, or any number of other things? And what a ViewModel was really threw me! I often felt paralyzed about how to apply a pattern, which greatly slowed me down. I eventually discovered that while there are some rules you must not break, many things are also permissible once you understand the purposes behind a pattern.

Oh, how I wish I had had access to Pieter’s book back then! He would have saved me a ton of time and spared me so much confusion.

I have interacted with Pieter for many years through the .NET community, and I know the size and scope of projects that he has been involved with. For that reason, I’m confident he’s well suited to not only explain the MVVM pattern but to do so in a way that conveys the real-world application of it. This book will help you understand why the pattern exists, and whether to use it or not.

Of course, I’m thrilled that Pieter is teaching MVVM while also introducing you to the awesome power of .NET MAUI for building mobile and desktop applications. MVVM is by far the most common pattern we see used with .NET MAUI and is what we use in most of our product samples at Microsoft.

I can’t wait to see what you build with .NET MAUI! Happy coding.

David Ortinau

Principal Product Manager @ Microsoft for .NET MAUI

Contributors

About the author

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, trainer, and blogger at blog.pieeatingninjas.be. Pieter has been awarded the Microsoft MVP Award since 2017, reflecting his unwavering passion and expertise in serving the community.

Thank you, Stefanie, my constant, not just in the process of writing this book but in every step of life. Your unwavering love, encouragement, and belief in me have been the driving force behind everything I do and achieve, not just this book. I cannot measure your impact in mere words. Thanks also to my parents, who gave my brothers and me endless opportunities and a strong foundation.

About the reviewer

Gerald Versluis is a Senior Software Engineer at Microsoft working on .NET MAUI. Since 2009 Gerald has been working on a variety of projects, ranging from frontend to backend and anything in between that involve C#, .NET, Azure, ASP.NET and all kinds of other .NET technologies. At some point, he fell in love with cross-platform and mobile development with Xamarin, now .NET MAUI. Since that time, he has become an active community member, producing content online and presenting about all things tech at conferences all around the world.

Gerald can be found on X (formerly Twitter) @jfversluis, blogging at https://blog.verslu.is, or on his YouTube channel: https://youtube.com/@jfversluis.

Table of Contents

Preface

Part 1: Key Concepts and Components

1

What Is the MVVM Design Pattern?

Technical requirements

Looking at MVVM’s core components

Model

View

ViewModel

Commands

Data binding

Separation of concerns matters

Maintainability

Testability

MVVM in action

The code-behind approach

Using MVVM

Common misconceptions about MVVM

There should be no code in the code-behind

The Model should exclusively be a DTO, a domain entity, or a POCO

The View and the ViewModel should not know each other

MVVM is too complex and used only for large applications

Summary

2

What is .NET MAUI?

Technical requirements

.NET MAUI in a nutshell

Reminiscent of Xamarin.Forms

Cross-platform UI and more

How does it work?

Native apps with .NET

.NET MAUI, another abstraction layer

Creating your first .NET MAUI app

Setting up your machine

Hello “Recipes!” app

Summary

Further reading

3

Data Binding Building Blocks in .NET MAUI

Technical requirements

Key components for data binding

Elements of data binding

BindableObject

BindableProperty

BindingContext

Data binding in practice

Binding modes and the INotifyPropertyChanged interface

Binding modes in .NET MAUI

INofityPropertyChanged

Different binding modes in action

Handling interactions with the ICommand interface

The ICommand interface

Putting it into action

Summary

Further reading

4

Data Binding in .NET MAUI

Technical requirements

ValueConverters and StringFormat

Creating and using ValueConverters

Fallbacks

TargetNullValue

FallbackValue

Element and relative binding

Element binding

Relative binding

Multi-bindings

Multi-binding StringFormat

IMultiValueConverter

Compiled bindings

Summary

Further reading

5

Community Toolkits

Technical requirements

The MVVM Toolkit

ObservableObject

RelayCommand

Source Generators

The .NET MAUI Community Toolkit

Converters

Behaviors

Other popular frameworks

Contributing to the community

Summary

Further reading

6

Working with Collections

Technical requirements

Using BindableLayout

What to show and how to show it

Dynamically choosing a DataTemplate at runtime

The ICollectionChanged interface

The ICollectionChanged interface and binding modes

Using the ObservableCollection

Working with CollectionView

Displaying grouped data

Selecting items

Incrementally loading data

Other common interactions

Summary

Further reading

Part 2: Building a .NET MAUI App Using MVVM

7

Dependency Injection, Services, and Messaging

Technical requirements

Inversion of Control through Dependency Injection

Dependency Injection

Registering, resolving, and injecting services

Registering services

Resolving and injecting services

Applying Dependency Injection

Messaging

WeakReferenceMessenger

Summary

Further reading

8

Navigation in MVVM

Technical requirements

About .NET MAUI Shell

Setting up Shell

Routing

Supporting Dependency Injection

Setting up navigation in a .NET MAUI Shell app

Creating an INavigationService interface

Creating and using a NavigationService

Passing parameters

Hooking into navigation

Setting up navigation without .NET MAUI Shell

Passing results back

Summary

Further reading

9

Handling User Input and Validation

Technical requirements

Implementing input validation on ViewModels

Using the ObservableValidator

Visualizing validation errors with triggers

Prompts and alerts

Confirming or canceling navigation

Summary

Further reading

10

Working with Remote Data

Technical requirements

Revisiting the model architecture

Updates to the codebase

Always return a result

Adding repository interfaces

API communication with Refit

Getting started with Refit

Creating API interfaces

Integrating Refit

API communication from ViewModels

Showing a loading indicator

Handling failures

Summary

Further reading

Part 3: Mastering MVVM Development

11

Creating MVVM-Friendly Controls

Technical requirements

Building a custom control with bindable properties

Implementing FavoriteControl

Animating state changes

Enabling interactions on custom controls

User actions and reflecting state

Adding command-based interactions

Working with control templates

Accessing elements from a template

Summary

Further reading

12

Localization with MVVM

Technical requirements

Working with cultures, resource files, and localization

Getting the user’s culture

Setting a different culture

Displaying formatted data

What are Resources Files?

Getting localized resources on the screen

Looking at a localization solution for MVVM

The Localization project

The Localization.Maui project

Using the LocalizedResourcesProvider and LocalizationManager

Using a custom Translate markup extension

Fetching localized data from APIs

Summary

Further reading

13

Unit Testing

Technical requirements

The importance of unit testing

Setting up a unit test project

Creating a unit test project

Creating unit tests

Looking at data-driven tests

Generating data with Bogus

Mocking dependencies with Moq

Applying mocking in our ViewModel tests

Thin UI, deep tests

Testing MAUI-specific code

Summary

Further reading

14

Troubleshooting and Debugging Tips

Technical requirements

Common data binding issues

Checking the Output and XAML Binding Failures window

Debugging with a DoNothingConverter

Troubleshooting collections

The data binding pitfall on Behaviors

Services and Dependency Injection pitfalls

Unable to resolve service for type

No parameterless constructor defined for type

Incorrect service registration

Frequent custom control and converter problems

Troubleshooting bindable properties

Binding to the BindingContext

Value converter issues

Summary

Further reading

Index

Other Books You May Enjoy

Part 1: Key Concepts and Components

In this part, we start by discussing the Model-View-ViewModel design pattern without tying it to a specific platform. Next, we'll introduce the .NET MAUI framework and highlight why it works so well with MVVM. As we move forward, you'll learn about the benefits of community toolkits and get hands-on experience with collections. This foundation sets you up for more advanced topics later on.

This part has the following chapters:

Chapter 1, The MVVM Design PatternChapter 2, The .NET MAUI FrameworkChapter 3, Data Binding Building Blocks in .NET MAUIChapter 4, Data Binding in .NET MAUIChapter 5, Community ToolkitsChapter 6, Working with Collections