Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 42 ยท Projects and Practice

Project: Notes App

Build a complete notes app in .NET MAUI with MVVM, search, pinning and SQLite storage: project layout, XAML pages, a tested core library and a runnable C# stand-in of the whole app logic.

A notes app is the best first project: it needs lists, forms, navigation, persistence and search, which are the pieces almost every real app uses. In this project you design the app, write the core logic as a testable library, and see the XAML that presents it. The core runs here as plain C#, so you can try it; the XAML and MAUI setup are read-only.

MAUI apps need a device or emulator, so the pages and the SQLite package cannot run on this site. The core logic (models, repository interface, view model rules) is real, working C# which you can paste into a library project. The runnable examples use an in-memory repository where the app would use SQLite.

Features

  • List notes, newest first, with pinned notes at the top.
  • Create, edit and delete a note (swipe to delete).
  • Search by title or text.
  • Notes survive restarts (SQLite).
  • Works in light and dark mode.

Architecture

flowchart LR
    V["Pages (XAML)"] --> VM["ViewModels"]
    VM --> R["INoteRepository"]
    R --> S["SqliteNoteRepository"]
    R --> M["InMemoryNoteRepository (tests)"]

The view model depends on an interface, so tests and this lesson use the in-memory version.

Solution layout:

TEXT
NotesApp.sln
  NotesApp.Core/        Note.cs, INoteRepository.cs, NotesViewModel.cs
  NotesApp/             MauiProgram.cs, Pages/, SqliteNoteRepository.cs
  NotesApp.Tests/       NotesViewModelTests.cs

The model and repository

C#
public class Note
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public string Body { get; set; } = "";
    public bool IsPinned { get; set; }
    public DateTime UpdatedAt { get; set; }
}

public interface INoteRepository
{
    Task<List<Note>> GetAllAsync();
    Task SaveAsync(Note note);      // insert when Id == 0, otherwise update
    Task DeleteAsync(Note note);
}

The real SQLite repository (with the sqlite-net-pcl package, see SQLite Local Database) maps these members almost one to one:

C#
public class SqliteNoteRepository : INoteRepository
{
    private SQLiteAsyncConnection? _db;

    private async Task<SQLiteAsyncConnection> GetDb()
    {
        if (_db is not null) return _db;
        string path = Path.Combine(FileSystem.AppDataDirectory, "notes.db3");
        _db = new SQLiteAsyncConnection(path);
        await _db.CreateTableAsync<Note>();
        return _db;
    }

    public async Task<List<Note>> GetAllAsync() => await (await GetDb()).Table<Note>().ToListAsync();
    public async Task SaveAsync(Note note) => await (await GetDb()).InsertOrReplaceAsync(note);
    public async Task DeleteAsync(Note note) => await (await GetDb()).DeleteAsync(note);
}

(For Id auto-increment, mark it [PrimaryKey, AutoIncrement].)

The view model

The view model holds the rules: ordering, searching and saving. Run it:

C# Core logic: repository and view model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The in-memory repository keeps the same list instance of Note objects, which is why toggling IsPinned works without a real update. A SQLite repository would persist the change in SaveAsync; the view model code stays identical, which is the point of the interface.

The list page

With the MVVM Toolkit the view model uses ObservableObject, [ObservableProperty] and [RelayCommand] instead of manual plumbing. The page is mostly XAML:

XML
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:NotesApp.ViewModels"
             xmlns:core="clr-namespace:NotesApp.Core;assembly=NotesApp.Core"
             x:Class="NotesApp.Pages.NotesPage"
             x:DataType="vm:NotesViewModel"
             Title="Notes">

    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Add" Command="{Binding NewNoteCommand}" />
    </ContentPage.ToolbarItems>

    <Grid RowDefinitions="Auto,*" Padding="12" RowSpacing="8">
        <SearchBar Placeholder="Search notes" Text="{Binding SearchText}" />

        <CollectionView Grid.Row="1" ItemsSource="{Binding Notes}"
                        SelectionMode="Single"
                        SelectedItem="{Binding SelectedNote}"
                        SelectionChangedCommand="{Binding OpenNoteCommand}">
            <CollectionView.EmptyView>
                <Label Text="No notes yet. Tap Add." HorizontalOptions="Center" />
            </CollectionView.EmptyView>
            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="core:Note">
                    <SwipeView>
                        <SwipeView.RightItems>
                            <SwipeItems>
                                <SwipeItem Text="Delete" BackgroundColor="Red"
                                           Command="{Binding Source={RelativeSource AncestorType={x:Type vm:NotesViewModel}}, Path=DeleteCommand}"
                                           CommandParameter="{Binding .}" />
                            </SwipeItems>
                        </SwipeView.RightItems>
                        <VerticalStackLayout Padding="8" Spacing="2">
                            <Label Text="{Binding Title}" FontAttributes="Bold" />
                            <Label Text="{Binding Body}" MaxLines="2" LineBreakMode="TailTruncation"
                                   TextColor="{AppThemeBinding Light=Gray, Dark=LightGray}" />
                        </VerticalStackLayout>
                    </SwipeView>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </Grid>
</ContentPage>

Notes on the details: x:DataType on both the page and the template turns on compiled bindings; the RelativeSource binding reaches the page's view model from inside the row template; EmptyView is the friendly empty state; and AppThemeBinding handles dark mode (see Themes and Dark Mode).

Registering everything

C#
public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder.UseMauiApp<App>();

    builder.Services.AddSingleton<INoteRepository, SqliteNoteRepository>();
    builder.Services.AddSingleton<NotesViewModel>();
    builder.Services.AddTransient<NoteEditViewModel>();
    builder.Services.AddSingleton<NotesPage>();
    builder.Services.AddTransient<NoteEditPage>();

    return builder.Build();
}

The repository is a singleton so there is one database connection; the edit page and view model are transient so each edit starts clean.

Tests

The rules in the view model are easy to cover (see Unit Testing View Models):

C#
[Fact]
public async Task PinnedNotesComeFirst()
{
    var vm = new NotesViewModel(new InMemoryNoteRepository());
    await vm.AddAsync("A", "");
    await vm.AddAsync("B", "");
    await vm.TogglePinAsync(vm.Notes.Single(n => n.Title == "A"));

    Assert.Equal("A", vm.Notes[0].Title);
}

[Fact]
public async Task EmptyTitleIsRejected()
{
    var vm = new NotesViewModel(new InMemoryNoteRepository());
    await Assert.ThrowsAsync<ArgumentException>(() => vm.AddAsync("  ", "text"));
}

Extension ideas

  1. Autosave drafts. Save the edit form to Preferences every few seconds.
  2. Tags and filters. Add a Tags column and a filter chip row.
  3. Export. Share a note as text with Share.Default.RequestAsync.
  4. Cloud sync. Add a REST client and a LastModified timestamp for conflict resolution.
  5. Reminders. Local notifications at a chosen time.
  6. Biometric lock. Hide the list until the user authenticates.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the view model depend on INoteRepository instead of the SQLite class?

    The interface decouples the rules from storage, so you can test without a database and swap storage later.
  2. 2. What does EmptyView on a CollectionView show?

    EmptyView is the friendly placeholder for an empty list.
  3. 3. Why register the edit page as transient?

    A transient registration creates a new instance each time, so a previous edit does not leak into the next one.
  4. 4. Where does the ordering rule 'pinned first, then newest' belong?

    Rules in the view model are plain C# and covered by unit tests.

Summary

  • Separate the app into Core (models, interfaces, view models), the MAUI app and tests.
  • The view model owns the rules (validation, search, ordering); the repository owns storage.
  • CollectionView, SwipeView, SearchBar and compiled bindings make a polished list screen.
  • Register singletons for shared services and transients for per-visit pages and view models.

Next: Project: Weather App