Skip to content

Blazor: Getting Started

Sukhrob Ilyosbekov edited this page Oct 31, 2021 · 5 revisions

Setup

Install nuget package MagicMvvm.Blazor

$ dotnet add package MagicMvvm.Blazor

Add service MVVM Blazor to IServiceCollection container.

In Blazor WebAssembly register service in Program.cs

builder.services.AddMvvmBlazor();

In Blazor Server register service in method ConfigureServices in Startup.cs

services.AddMvvmBlazor();

View Component

All view components must inherit from ViewBase<T> where T is data type of the ViewModel class.

Sample counter component.

@page "/counter"
@inherits ViewBase<CounterViewModel>

<h1>Counter</h1>

<p>Current count: @DataContext.CurrentCount</p> @* Access to ViewModel's CurrentCount property *@

<button class="btn btn-primary" @onclick="@DataContext.IncrementCount">Click me</button>

ViewModel

ViewModel class must inherit from ViewModelBase. View components can access to its view model properties by DataContext property.

Sample below code shows ViewModel of the component counter

public class CounterViewModel : ViewModelBase
{
    private int _cuurentCount;
    public int CurrentCount 
    { 
        get => _cuurentCount; 
        set => SetProperty(ref _cuurentCount, value); // Notifies to UI when property has been changed
    }

    public void IncrementCount()
    {
        CurrentCount++;
    }
}

Life cycle methods

List of life cycle methods of the ViewModel:

  • OnInitialized
  • OnInitializedAsync
  • OnParametersSet
  • OnParametersSetAsync
  • ShouldRender
  • OnAfterRender
  • OnAfterRenderAsync
  • SetParametersAsync

You can also call StateHasChanged in ViewModel class. Method StateHasChanged explicitly notifies the component that its state has changed. When applicable, this will cause the component to be re-rendered.

Sample Project

Check out sample blazor project where demonstrated features.

Clone this wiki locally