Summary
Highlights
This video continues the .NET MAUI Beginner Series, focusing on building responsive and reactive user interfaces using MVVM (Model-View-ViewModel). MVVM is a popular architecture pattern for XAML applications that enables data binding, allowing the UI to respond to code-behind changes and vice versa. The View displays data, the ViewModel represents what to display and handles interactions, and the binding system connects them.
The tutorial demonstrates updating the existing application to integrate MVVM. It starts by creating a 'ViewModel' folder and a 'MainViewModel' class. Initially, the I 'Notify Property Changed' interface is used to manually implement property change notifications, showing how properties are set and how the UI is updated.
To simplify MVVM implementation, the video introduces the 'CommunityToolkit.Mvvm' NuGet package. This toolkit provides `ObservableObject` and `ObservableProperty` attributes, which use source generators to automatically implement I 'Notify Property Changed' for properties, reducing boilerplate code and optimizing performance. The `ICommand` attribute is also introduced for handling UI interactions via commands, abstracting event handling.
The 'MainViewModel' is then connected to the 'MainPage' XAML view. A namespace for the ViewModel is added to the XAML, and `x:DataType` is used to associate the ViewModel with the content page. The `Text` property from the ViewModel is data-bound to an `Entry` control, and an `AddCommand` is created to add items to an `ObservableCollection` in the ViewModel.
To properly manage the ViewModel instances, dependency injection is used. The 'MauiProgram.cs' file is modified to register the 'MainPage' and 'MainViewModel' as singletons using `builder.services.AddSingleton`. This ensures that instances are created once and automatically injected where needed, promoting a cleaner architecture.
The tutorial extends the functionality by adding a 'DeleteCommand' to the ViewModel for removing items from the list. This command takes a string parameter. In the XAML, a `SwipeItem` is configured to use this 'DeleteCommand', utilizing an ancestry binding to locate the ViewModel and pass the selected item as a command parameter. This demonstrates how to interact with the ViewModel from nested UI elements.
The video concludes by showcasing the fully functional application with adding and deleting items using MVVM and data binding. The next video in the series will cover navigation between pages in .NET MAUI applications.