MVVM Pattern and Data Binding in .NET MAUI
The Model-View-ViewModel (MVVM) pattern is the foundation of modern .NET MAUI development. It separates the user interface from the business logic, making your applications more maintainable, testable, and scalable [citation:14].
⚡ Key Insight: MVVM is not just a pattern—it's an architecture that enables true separation of concerns in cross-platform applications [citation:14].
Understanding MVVM
MVVM is a software architectural pattern that separates an application into three main components [citation:14]:
- Model: The data and business logic layer
- View: The user interface (XAML)
- ViewModel: The bridge that connects the Model and View
// Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// ViewModel
public class ProductViewModel : ObservableObject
{
private Product _product;
public Product Product
{
get => _product;
set => SetProperty(ref _product, value);
}
private bool _isBusy;
public bool IsBusy
{
get => _isBusy;
set => SetProperty(ref _isBusy, value);
}
public ICommand LoadProductCommand { get; }
public ProductViewModel()
{
LoadProductCommand = new AsyncRelayCommand(LoadProductAsync);
}
private async Task LoadProductAsync()
{
IsBusy = true;
// Load product logic
IsBusy = false;
}
}
Data Binding in XAML
Data binding is the mechanism that connects the ViewModel to the View. It automatically synchronizes data between the two [citation:1].
<!-- Basic Data Binding -->
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ACUAMITCA.Views.ProductPage">
<VerticalStackLayout>
<Label Text="{Binding Product.Name}" FontSize="24" FontAttributes="Bold" />
<Label Text="{Binding Product.Price, StringFormat='Price: {0:C}'}" />
<Button Text="Load Product" Command="{Binding LoadProductCommand}" />
<ActivityIndicator IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}" />
</VerticalStackLayout>
</ContentPage>
Advanced Data Binding Techniques
Value Converters
Value converters transform data between the ViewModel and the View. They're essential for formatting or converting data types [citation:11].
public class BoolToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool boolValue && boolValue)
return Colors.Green;
return Colors.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is Color color && color == Colors.Green;
}
}
<!-- Using the converter -->
<Label Text="Status" TextColor="{Binding IsActive, Converter={StaticResource BoolToColorConverter}}" />
Multi-Binding
Multi-binding allows you to combine multiple data sources into a single binding [citation:11].
<MultiBinding Converter="{StaticResource TotalConverter}">
<Binding Path="Quantity" />
<Binding Path="UnitPrice" />
</MultiBinding>
Navigation in MVVM
In a well-structured MVVM application, navigation logic should reside in the ViewModel, not the View [citation:14].
public interface INavigationService
{
Task NavigateToAsync(string pageKey, object parameter = null);
Task GoBackAsync();
}
public class NavigationService : INavigationService
{
private readonly IServiceProvider _serviceProvider;
public NavigationService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task NavigateToAsync(string pageKey, object parameter = null)
{
var page = _serviceProvider.GetRequiredKeyedService<Page>(pageKey);
if (page.BindingContext is IQueryAttributable attributable)
{
attributable.ApplyQueryAttributes(parameter as IDictionary<string, object>);
}
await Shell.Current.GoToAsync($"//{pageKey}", parameter);
}
}
Best Practices
✅ Keep ViewModels Thin
The ViewModel should only contain UI state and commands. Business logic belongs in services.
✅ Use ObservableObject
Implement INotifyPropertyChanged using ObservableObject from the Community Toolkit.
✅ Use ICommand for Actions
Use AsyncRelayCommand and RelayCommand for button actions and other UI interactions.
✅ Test ViewModels
MVVM makes unit testing easy. Test your ViewModels without the UI.
Conclusion
📌 Key Takeaway: MVVM is the recommended architecture for .NET MAUI applications. It provides clear separation of concerns, making your code more maintainable, testable, and scalable [citation:14].