🏗️ Architecture & Data
MVVM Architecture Pattern
ObservableObject, [ObservableProperty], [RelayCommand], Commands.

MVVM Architecture Overview

Model = data and business logic. ViewModel = prepares data for display. View = XAML UI that binds to the ViewModel. The ViewModel never references the View — communication is entirely through bindings.

Full Weather ViewModel

csharp
public partial class WeatherViewModel : ObservableObject
{
    private readonly IWeatherService _svc;

    [ObservableProperty] bool _isLoading;
    [ObservableProperty] string _errorMessage = "";
    [ObservableProperty] ObservableCollection<Forecast> _forecasts = [];

    public WeatherViewModel(IWeatherService svc) => _svc = svc;

    [RelayCommand]
    async Task LoadAsync()
    {
        IsLoading = true;
        ErrorMessage = "";
        try
        {
            var data = await _svc.GetForecastAsync();
            Forecasts = new ObservableCollection<Forecast>(data);
        }
        catch (Exception ex) { ErrorMessage = ex.Message; }
        finally { IsLoading = false; }
    }
}
💡
Inject IWeatherService (an interface) rather than WeatherService (a concrete class). This lets you swap in a MockWeatherService during unit tests without touching ViewModel code.

Key Takeaways

MVVM separates data (Model), logic (ViewModel), and display (View)
CommunityToolkit.Mvvm source-generates all boilerplate with attributes
Inject interfaces into ViewModels — enables unit testing with mocks
Never reference View types in ViewModel — communicate only through bindings
Lesson 16 of 30Architecture & Data
← Previous Next Lesson →