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
[View (XAML)] β [ViewModel (C#)] β [Model (C#)]
- 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; }
}
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" />
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));
}
π 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;
}
β 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);
}
}
- 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" />
- 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
MVVM Flow:
User Input β View β ViewModel β Model
β
Data Binding
β
View Update
β 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.
Top comments (0)