close
close

Streamlining MVVM in .NET MAUI with Relay Commands

.NET MAUI simplifies cross-platform app development with a modern, consistent API. One of the features that the Model-View-ViewModel (MVVM) pattern in .NET MAUI enhances is the use of relay commands. These commands help bind user actions in the view to methods defined in the ViewModel.

What are relay commands?

Relay commands are a type of ICommand implementation that allows you to bind the UI events to commands in your ViewModel, eliminating the need for event handlers and making your code cleaner and more maintainable. They are particularly useful in MVVM applications where you want to maintain strict separation between the view and the ViewModel.

How relay commands work

The RelayCommand attribute can be used to annotate methods in a partial class, automatically generating the necessary command properties. For example:

C#

(RelayCommand)
private void GreetUser()
{
    Console.WriteLine("Hello!");
}
Go to full screen mode

Exit full screen mode

This will generate a command property in your ViewModel that you can bind to from your view.

Command parameters and asynchronous commands

Relay commands can also work with parameters and asynchronous methods. When a method has a parameter, the command generated will be of type IRelayCommandWhere T is the type of parameter1. For asynchronous methods, the command is implemented IAsyncRelayCommand or IAsyncRelayCommand if it has a parameter.

The prism approach

Prism is a well-known framework for building loosely coupled, maintainable and testable applications in WPF, Xamarin Forms and now in .NET MAUI. It provides developers with a robust set of tools to implement the MVVM pattern, including DelegateCommand And CompositeCommand for handling commands within the ViewModel. However, this approach often requires a significant amount of boilerplate code, which can be cumbersome and increase the complexity of the application.

How .NET’s MVVM Toolkit reduces MAUI code

The .NET MAUI MVVM approach, powered by the Microsoft MVVM Toolkit, simplifies command deployment through the use of relay commands. This reduces the need for the extensive code typically associated with the Prism approach. Here’s how:

  • Less boilerplate: Relay commands require less boilerplate code than Prism’s DelegateCommandbecause they don’t need any explicit implementation CanExecute And Execute methods.
  • No event handlers: Relay commands eliminate the need for event handlers in the underlying code, which are often needed in Prism to invoke commands.
  • Simplified execution of commands: Command execution is easier with relay commands because they allow direct method calls within the ViewModel.

Example: Simplified command implementation

Here’s a side-by-side comparison of a command implementation using Prism and .NET MAUI’s relay commands:

C#

// Prism approach
public class MyViewModel : BindableBase
{
    private DelegateCommand _myCommand;
    public DelegateCommand MyCommand =>
        _myCommand ?? (_myCommand = new DelegateCommand(ExecuteCommand, CanExecuteCommand));

    private void ExecuteCommand() { /* Command logic */ }
    private bool CanExecuteCommand() { /* CanExecute logic */ }
}

// .NET MAUI's relay command approach
public partial class MyViewModel
{
    (RelayCommand)
    private void MyCommand()
    {
        // Command logic here
    }
}
Go to full screen mode

Exit full screen mode

As demonstrated, the .NET MAUI approach results in a more concise and readable ViewModel.

The Microsoft MVVM Toolkit framework

The Microsoft MVVM Toolkit framework is a set of tools that simplifies the implementation of the MVVM pattern in .NET applications. It provides developers with a robust foundation for building responsive, maintainable, and testable applications. The toolkit includes features such as ObservableObject, RelayCommandAnd AsyncRelayCommandwhich are essential for creating a clean and efficient ViewModel.

How .NET MAUI Adopts the MVVM Toolkit

.NET MAUI’s MVVM approach is heavily influenced by the Microsoft MVVM Toolkit framework. It leverages the toolkit’s features to streamline the development process and reduce the boilerplate code typically associated with MVVM applications. This allows developers to focus more on the business logic rather than the intricacies of MVVM implementation.

For example the RelayCommand attribute in .NET MAUI is a direct adoption of the MVVM Toolkit. It automatically generates command properties, eliminating the need for manual implementation ICommand properties and associated therewith CanExecute And Execute methods.

Benefits of using the MVVM Toolkit in .NET MAUI

By integrating the Microsoft MVVM Toolkit framework, .NET MAUI offers several benefits:

  • Simplified display model: Using source generators and attributes from the MVVM Toolkit reduces the complexity of the ViewModel.
  • Improved maintainability: With less code to manage, the ViewModel becomes easier to maintain and evolve over time.
  • Improved testability: The separation of concerns is clearer, making it easier to write unit tests for the ViewModel and Model.
  • Streamlined development: Developers can quickly develop new features without worrying about the underlying command infrastructure.

Conclusion

The adoption of the Microsoft MVVM Toolkit’s relay commands in .NET MAUI has taken the complexity out of the MVVM pattern. By reducing the amount of code required to implement commands, developers can enjoy a more streamlined development experience, allowing them to focus on creating feature-rich and responsive applications.