DEV Community

Cover image for Bye old ways, Hello MVVM Community Toolkit
Nicolas
Nicolas

Posted on • Updated on

Bye old ways, Hello MVVM Community Toolkit

If you are a .NET Dev , have worked with Xamarin - MAUI , WPF etc... and you also use Model-View-ViewModel (MVVM) pattern in your apps you probably know the frustration of working with Observable ViewModels and are very familiar with this code :

    [Preserve(AllMembers = true)]
    [DataContract]
    public class BaseViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }


    }
Enter fullscreen mode Exit fullscreen mode

This is something we all got used to some decide to go for external libraries but It feels like swapping one form of complexity with another.

I am back and I have Great News, after this article You will never have to manually deal with the code above ever again Thanks to the MVVM Community Toolkit.

You can read more about the MVVM Toolkit library here

Today I am just going to show you how to get started with the automatic Command and Property Generator.

Is it complicated?

No, one of the reasons I love this library is because it has no learning curve, just plug and play.

How does it work?

It's pretty straight forward ,if you have been around long enough you might know "Fody OnPropertyChanged " this library was and still is great but with fody you still had to create properties and commands yourself.

This is were the MVVM Toolkit gets interesting behind the scene e.g the new MVVM Toolkit preview version uses C# source code generators to create a partial class of your view model, this generated class will implement INotifyPropertyChanged and contain the properties and commands you want to generator and in addition the generated properties will call or invoke onPropertyChange when ever new values are set.

The final generated source code isn't that much of magic or different from they way you would traditionally do it, this library just increases your productivity by writing half of your code for you 😁😎.

for Additional information about this mvvm toolkit preview you can also check this blog

Alright enough talking lets jump into the code

Lets start with making your view Model Observable

  • Create your View Model class.
  • Make it partial .
  • Make your View Model Inherit from ObservableObject, this is a class found in the mvvm community toolkit library.

your ViewModel should look like this :

public partial class MyViewModel : ObservableObject
{

}
Enter fullscreen mode Exit fullscreen mode

Next if you want a property in ViewModel to be Observable

Community Toolkit generates Properties and Commands by Convention.You just have to create a instance variable that follow C# conventions (class variables are camel cased and or optionally prefixed with underscore _ )
e.g

 private List<Bot> bots; 
Enter fullscreen mode Exit fullscreen mode

or

private List<Bot> _bots; 
Enter fullscreen mode Exit fullscreen mode

Then once you done creating your variable. Mark it as an ObservableProperty with the ObservablePropertyAttribute

e.g

[ObservableProperty]
private List<Bot> bots;
Enter fullscreen mode Exit fullscreen mode

Thats it The library will automatically generate a public Observable property of this field. The code is immediately generated so you can immediately access the Property e.g in the class you can call e.g.

// accessing the property

var firstBotName = Bots[0].Name;

//rest of your code

Enter fullscreen mode Exit fullscreen mode

That's Soo Cool right ?? Yes. You will be able to Bind it to your XAML the same way you use to e.g :

<ListView ItemSource="{Binding Bots}">
// Additional logic.....
Enter fullscreen mode Exit fullscreen mode

There are additional attributes you can use to decorate your property with additional behaviour you can read about them here

This is not where all the fun ends. In a Traditional View Model you would have to create Commands then create actions that will be called by the commands when they are executed. This complicates our ViewModel. The toolkit provides a way to automatically generate your commands for you , you only have focus on writing your actions.

Example Lets say we want to create a command to call an action to do something .

Firstly we need to create our action method

public void DoSomething()
{

{
Enter fullscreen mode Exit fullscreen mode

Next to automatically create a Command using Mvvm Toolkit, we are going to have to decorate our method with [RelayCommand] attribute (this attribute use to be called ICommand in the toolkit and was renamed to RelayCommand in preview 4 ). Our class will now look like this

[RelayCommand]
public void DoSomething()
{

{
Enter fullscreen mode Exit fullscreen mode

Remember Community Toolkit generates Properties and Commands by Convention so When we create a method called DoSomething our Generated Command will be DoSomethingCommand

If our Method is async and we suffixed it with Async e.g DoSomethingAsync. The Async Suffix will be disregarded when the command is generated and the command will be generated as DoSomethingCommand with this in mind when you want to bind you command to your UI Control it would look something like this :

<Button ... Command="{Binding DoSomethingCommand}"/>
Enter fullscreen mode Exit fullscreen mode

Your action can take in arguments as well the source code generated will take that into consideration.

Now our ViewModels will look cleaner, simple and easy to work with.
This is so great ,It's still in preview but it's already making waves.

Top comments (0)