This series assumes the developer is familiar with .NET MAUI, the Model-View-ViewModel pattern, and has worked through one or more tutorials such as the excellent James Montemagno's Workshop.
- Part 1 - Adding the View Model
- Part 2 - (The Problem With) Basic Unit Testing
- Part 3 - Adding the Model
- Part 4 - Putting the View in Its Place
- Part 5 - Restyling From Scratch
- Part 6 - Revisiting Unit Testing
- Part 7 - Deploying, the Other People's Links Edition
Moving the View
Compared to the last part, this one's really short.
Our app has one view, MainPage, sitting in the root of the project. Like the rest of this series, that's fine for a small app with just a few views. But let's keep our app tidy and pretend it's going to have a dozen views.
Which might be an awful lot for a mobile app.
Maui.Progression project, add a folder named "Views" and move the MainPage files (
MainPage.xaml.cs) into it. When prompted to adjust namespaces, choose Yes.
Trickery, trickery, trickery1 Neither of our files' namespaces got updated.
MainPage.xaml.cs and update the namespace.
using Maui.Progression.ViewModels; namespace Maui.Progression.Views;
MainPage.xaml and update the page's x:Class namespace.
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Maui.Progression.Views.MainPage"
We also need to edit
MauiProgram.cs to add
using Maui.Progression.DomainServices; using Maui.Progression.DomainServices.Interfaces; using Maui.Progression.ViewModels; using Maui.Progression.Views;
AppShell.xaml "local" namespace.
<?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="Maui.Progression.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Maui.Progression.Views"
Run the program and the tests. Et voila! it works.
I know, I know. "Jeez, that was easy, what was the point?"
The point is that we now have a well-organized application, which increases maintainability. We're following a View-Model-ViewModel pattern, and our Views, View Models, and Models are corralled into their metaphorical pens. We also saw just how pervasive and important the namespaces are, and that--unlike some other refactoring--Visual Studio doesn't (today) catch everything.
Next Up: Styles!
From The Far Side by Gary Larson