-
Notifications
You must be signed in to change notification settings - Fork 2
Blazor: Getting Started
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();
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 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 _currentCount;
public int CurrentCount
{
get => _currentCount;
set => SetProperty(ref _cuurentCount, value); // Notifies to UI when property has been changed
}
public void IncrementCount()
{
CurrentCount++;
}
}
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.
Explore sample blazor project where demonstrated features.