Using dotnet 3.1.100-preview2-014569
Ok consider the following example:
Create a new Blazor WebAssemply project from template, then add the following:
<
Here's a new solution in which I implement the INotifyPropertyChanged intereface in the BookService class. Why use this interface ?
It can be applied to other properties as well
Notifying clients that a property value has changed is essential part of good services, and this is not limited to only call the StateHasChanged solely for this purpose.
With the INotifyPropertyChanged intereface implemented, I can pass event data to registered or subscribing objects.
Important: Calling a method to update a property value like bookService.SetLoanedState(false) is a bad programming and an anti-patterns design. A property can have two accessors, get and set, and they should be used to get a value and to change a value. Methods have different roles...
BookService.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class BookService : INotifyPropertyChanged
{
private bool isLoaned;
public event PropertyChangedEventHandler PropertyChanged;
public int BookId { get; set; }
public string Title { get; set; }
public bool IsLoaned
{
get
{
return this.isLoaned;
}
set
{
if (value != this.isLoaned)
{
this.isLoaned = value;
NotifyPropertyChanged();
}
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
@page "/books"
@inject BookService bookService
@using System.ComponentModel
@if (bookService.IsLoaned)
{
Book loaned
}
else
{
Book returned
}
@code{
protected override void OnInitialized()
{
bookService.PropertyChanged += PropertyHasChanged;
}
private void PropertyHasChanged(object sender, PropertyChangedEventArgs args)
{
StateHasChanged();
}
}
@code {
// Code removed for brevity
private void LoanBookClicked()
{
bookService.IsLoaned = true;
}
private void ReturnBookClicked()
{
bookService.IsLoaned = false;
}
}
Hope this works...