Skip to content

MVVM ViewModels

Jan M edited this page Mar 13, 2021 · 3 revisions

Overview of the different base classes

1. The basic one: ViewModelBase

This is a very basic implementation and just provides a property public bool IsInitialized to state wether this instance has been set up using the InitializeAsync method. This method is automatically invoked when creating instances using the ViewModelFactory.

Example usage:

public class CalendarViewModel :
    ViewModelBase
{
    public override async Task InitializeAsync()
    {
        // some async logic like database access here...
    }
}

2. The model-dependent one: ViewModelBase<TModel>

The generic implementation extends the ViewModelBase by providing the InitializeAsync<TModel>(TModel model) method. This way it is possible to initialise your ViewModel instance directly with a model that is necessary for the instance anyways.

Example usage:

public class DetailsViewModel :
    ViewModelBase<Item>,
    IDetailsViewModel
{
    public Item Item
    {
        get => return GetValue<Item>();
        private set => SetValue(value);
    }
    public override async Task InitializeAsync(Item model)
    {
        Item = model;
    }
}

// Navigation example:
navigationService.ShowAsync<IDetailsViewModel, Item>(selectedItem);