MSDN Community

Windows Desktop Development Forum

How to implement MVVM in WPF without excessive boilerplate code?

Category: WPF Tags: MVVM, Boilerplate, Design Patterns, C#, XAML Started by: DevNinja88 On: 2023-10-27 10:35 AM
DN
Hello everyone,

I'm relatively new to WPF and have been trying to adopt the MVVM pattern as recommended for robust application architecture. However, I'm finding myself writing a lot of repetitive code for property changed notifications, command implementations, and basic ViewModel setup. This boilerplate is starting to feel overwhelming and makes the code less readable.

Are there any best practices or libraries you'd recommend to minimize this boilerplate? I've heard about libraries like MVVM Light, Prism, or Caliburn.Micro, but I'm not sure which one to choose or how to best integrate them. My main goal is to keep the code clean and maintainable.

Any advice or code examples would be greatly appreciated!
Reply Quote Like (15)
AC
Welcome to WPF!

You're definitely not alone in this. The boilerplate for MVVM in pure WPF can be substantial. Libraries are indeed the way to go.

MVVM Light is a good starting point. It's lightweight and provides utilities for Messenger, RelayCommand, and ViewModelBase. It's relatively easy to get up and running.

Prism is more of a comprehensive framework. It offers solutions for modularity, navigation, dependency injection, and more. It's powerful but can have a steeper learning curve.

Caliburn.Micro uses convention over configuration extensively, which can significantly reduce code, but it has its own unique way of doing things.

For minimizing boilerplate with property changed notifications specifically, you can use the `[NotifyPropertyChangedIn]` attribute from the `CommunityToolkit.Mvvm` package (which is the successor to MVVM Light). It generates the `OnPropertyChanged` calls for you at compile time.

using CommunityToolkit.Mvvm.ComponentModel;

public partial class MyViewModel : ObservableObject
{
    [ObservableProperty]
    private string _userName;

    [ObservableProperty]
    private int _userAge;
}
                    
This generates the necessary `UserName` and `UserAge` properties with notifications.
Reply Quote Like (22)
SG
I've been using Caliburn.Micro for a few years now, and it's fantastic for reducing boilerplate. Its "convention over configuration" approach means you often don't need explicit bindings or `INotifyPropertyChanged` implementations if you follow its naming conventions. For example, a property named `MyProperty` will automatically trigger a UI update if its backing field changes, and a method named `MyPropertyChanged` would be invoked. Commands are also handled implicitly with methods like `CanMyProperty` and `MyProperty` for `ICommand` bindings.

It takes a bit of getting used to, but once it clicks, development speed increases dramatically.
Reply Quote Like (18)

Post a Reply