DEV Community

Cover image for MVVM Pattern in C#
Taki
Taki

Posted on

1

MVVM Pattern in C#

The MVVM (Model-View-ViewModel) pattern is a powerful architectural pattern used primarily in C# and .NET applications, especially WPF (Windows Presentation Foundation), Xamarin, and MAUI. It promotes separation of concerns and enhances testability, scalability, and maintainability of UI applications.


πŸ”· What is MVVM?

MVVM stands for:

  • Model – Represents the application's data and business logic.
  • View – The UI (XAML files in WPF/Xamarin). It displays data and receives user input.
  • ViewModel – An abstraction of the View. It exposes data and commands to the View and handles UI logic.

πŸ” MVVM Flow Diagram

Image description

[View (XAML)] ⇄ [ViewModel (C#)] ⇄ [Model (C#)]
Enter fullscreen mode Exit fullscreen mode
  • View binds to properties/commands in the ViewModel.
  • ViewModel manipulates Model and updates View through data binding.
  • Communication is one-way or two-way binding, especially in WPF.

πŸ” Components Explained

1. Model

  • Represents data structures and business logic.
  • Often uses POCO classes (Plain Old CLR Objects).
  • No reference to UI or ViewModel.
public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

2. View

  • Defined in XAML.
  • Binds UI elements to ViewModel properties and commands.
  • Should not contain logic.
<TextBox Text="{Binding ProductName}" />
<Button Command="{Binding SaveCommand}" Content="Save" />
Enter fullscreen mode Exit fullscreen mode

3. ViewModel

  • Implements INotifyPropertyChanged for data binding.
  • Contains properties and commands used by the View.
  • Does not reference the View directly (testable & decoupled).
public class ProductViewModel : INotifyPropertyChanged
{
    private string _productName;
    public string ProductName
    {
        get => _productName;
        set
        {
            _productName = value;
            OnPropertyChanged(nameof(ProductName));
        }
    }

    public ICommand SaveCommand { get; }

    public ProductViewModel()
    {
        SaveCommand = new RelayCommand(SaveProduct);
    }

    private void SaveProduct()
    {
        // Logic to save product
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Enter fullscreen mode Exit fullscreen mode

πŸ›  Supporting Concepts

πŸ”Ή INotifyPropertyChanged

Enables the ViewModel to notify the View when a property changes.

πŸ”Ή ICommand

Allows ViewModel to expose commands to the View (e.g., button click handlers).

public class RelayCommand : ICommand
{
    private readonly Action _execute;
    private readonly Func<bool> _canExecute;
    public RelayCommand(Action execute, Func<bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
    public void Execute(object parameter) => _execute();
    public event EventHandler CanExecuteChanged;
}
Enter fullscreen mode Exit fullscreen mode

βœ… Benefits of MVVM

Benefit Description
πŸ”„ Data Binding Allows automatic UI updates when ViewModel changes.
πŸ§ͺ Testability ViewModel and Model are testable without UI.
πŸ”Œ Loose Coupling View and ViewModel are decoupled.
πŸ“¦ Reusability ViewModel can be reused with different Views.
🧹 Maintainability Clean separation improves maintainability.

⚠️ MVVM Anti-Patterns to Avoid

  • ViewModel becoming too fat (handling too much business logic).
  • Adding UI logic directly in the ViewModel (e.g., animations).
  • Binding directly to Model objects without abstraction.

πŸ“š MVVM in Frameworks

Framework MVVM Support
WPF Built-in and most common use case
Xamarin.Forms Strong support
MAUI Recommended pattern
WinUI Native MVVM with MVVM Toolkit
Avalonia Full MVVM pattern support

🧰 Tools & Libraries

  • MVVM Light Toolkit
  • Prism
  • CommunityToolkit.Mvvm (official .NET MVVM toolkit)
  • ReactiveUI

πŸ”š Summary

MVVM is ideal for UI-centric .NET apps. It separates responsibilities and enables cleaner code. Learning and applying MVVM effectively, especially with data binding and command patterns, is essential for building modern desktop and mobile applications in the .NET ecosystem.


πŸ”· MVVM vs MVC

πŸ” Quick Comparison Table

Aspect MVC (Model-View-Controller) MVVM (Model-View-ViewModel)
Best for Web apps (ASP.NET, Rails) Desktop/mobile apps (WPF, Xamarin, MAUI)
View ↔ Logic Binding Manual (Controller updates View) Automatic (Data Binding between View and ViewModel)
Controller Role Handles input, updates Model & selects View Replaced by ViewModel
ViewModel Role Not present Handles UI state, commands, and data binding
Data Binding Limited or manual Strong (supports One-Way / Two-Way)
Testability Controller is testable; View is not ViewModel and Model are easily testable
Tightness to View Controller often tightly coupled to View ViewModel is loosely coupled via bindings
Platform Fit ASP.NET MVC, Web APIs WPF, Xamarin, MAUI, UWP, WinUI

🧩 Conceptual Breakdown

MVC (Model–View–Controller)

  • Model – Business logic and data.
  • View – UI presentation (HTML, Razor, etc.).
  • Controller – Handles user input, updates model, and selects the view.

Example (ASP.NET MVC):

public class ProductController : Controller
{
    public ActionResult Details(int id)
    {
        var product = db.Products.Find(id);
        return View(product);
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Works well for web apps, where user interaction happens via HTTP requests.
  • Less focus on real-time UI state updates.

MVVM (Model–View–ViewModel)

  • Model – Business data and logic.
  • View – UI (XAML in WPF/Xamarin).
  • ViewModel – Exposes properties and commands bound to the View.

Example (WPF MVVM):

<TextBox Text="{Binding ProductName, Mode=TwoWay}" />
<Button Command="{Binding SaveCommand}" Content="Save" />
Enter fullscreen mode Exit fullscreen mode
  • Suited for rich UIs with real-time interactions, like desktop or mobile.
  • ViewModel handles UI logic without touching UI elements directly.

πŸ” Workflow Differences

MVC Flow:

User Input β†’ Controller β†’ Model β†’ Controller β†’ View β†’ User
Enter fullscreen mode Exit fullscreen mode

MVVM Flow:

User Input β†’ View β†’ ViewModel ↔ Model
                        ↓
                  Data Binding
                        ↓
                    View Update
Enter fullscreen mode Exit fullscreen mode

βœ… When to Use What

Use Case Pattern to Choose
Web apps with RESTful interaction MVC
Desktop/mobile apps (rich UI) MVVM
Need strong data binding support MVVM
Thin UI with server-rendered logic MVC
Building on WPF/Xamarin/MAUI MVVM

🧠 Summary

  • MVC is a better fit for web applications where user interaction follows a request/response pattern.
  • MVVM shines in desktop/mobile apps where real-time UI updates and state management are critical.
  • Both encourage separation of concerns but serve different interaction models and platforms.

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

Top comments (0)

AWS Security LIVE! Stream

Streaming live from AWS re:Inforce

Tune into Security LIVE! at re:Inforce for expert takes on modern security challenges.

Learn More