DEV Community

Rupesh Ghosh
Rupesh Ghosh

Posted on • Updated on

How to use Community Toolkit MVVM in Avalonia

Avalonia is an open-source, cross-platform .NET UI framework that enables developers to create desktop applications that run on Windows, macOS, and Linux. Avalonia provides built-in support for the Model-View-ViewModel (MVVM) pattern.

Setting Up the Project

Before we dive into using the MVVM Community Toolkit, we need to set up a basic Avalonia MVVM application. We can do this by creating a new project in Visual Studio or Rider and selecting the "Avalonia MVVM Application" project template, or via the .NET CLI

dotnet new avalonia.mvvm -o Sample -n Sample
Enter fullscreen mode Exit fullscreen mode

Using Community Toolkit MVVM in Avalonia

The Community Toolkit MVVM is a lightweight, flexible, and easy-to-use MVVM framework that provides basic infrastructure for implementing MVVM in .NET applications. It is maintained and published by Microsoft and is part of the .NET Foundation.

To use Community Toolkit MVVM in an Avalonia application, follow these steps:

  • Install the CommunityToolkit.Mvvm package from NuGet package manager or via .NET CLI
dotnet add package CommunityToolkit.Mvvm
Enter fullscreen mode Exit fullscreen mode
  • Remove Avalonia.ReactiveUI Package Reference from Sample.csproj
  • From Program.cs, Remove UseReactiveUI() extension method from BuildAvaloniaApp method.
public static AppBuilder BuildAvaloniaApp()
    => AppBuilder.Configure<App>()
Enter fullscreen mode Exit fullscreen mode
  • In ViewModels/ViewModelBase.cs, Inherit from ObservableObject.
public class ViewModelBase : ObservableObject
Enter fullscreen mode Exit fullscreen mode

Comparing Community Toolkit MVVM and Reactive UI

While both Community Toolkit MVVM and Reactive UI are popular MVVM frameworks for .NET applications, they have different strengths and weaknesses. Here are some trade-offs to consider when choosing between them:

  • Complexity: Reactive UI is a more complex and powerful framework than Community Toolkit MVVM. While Reactive UI provides advanced features for reactive programming and asynchronous data binding, it can be more difficult to learn and use, especially for developers who are new to reactive programming.

  • Performance: Reactive UI can be slower than Community Toolkit MVVM due to its reliance on reactive programming and the Rx library. While the performance difference may not be noticeable in small applications, it can become an issue in larger, more complex applications.

  • Flexibility: Reactive UI provides more flexibility and power than Community Toolkit MVVM, allowing developers to implement complex scenarios such as multi-threading, custom schedulers, and advanced data binding scenarios.

Latest comments (1)

msh2050 profile image

hope you will post some code example