Using dotnet 3.1.100-preview2-014569
Ok consider the following example:
Create a new Blazor WebAssemply project from template, then add the following:
<
books.razor (add a handler for the new onchange event of the book service )
@page "/books"
@inject BookService bookService
@if (bookService.isLoaned)
{
Book loaned
}
else
{
Book returned
}
@code{
protected override void OnInitialized()
{
bookService.OnChange += StateHasChanged;
}
}
BookService.cs (add an event action,change the property to readonly, add a setter, trigger event will NotifyStateChanged()
public class BookService
{
public event Action OnChange;
public int BookId { get; set; }
public string Title { get; set; }
public bool isLoaned { get; }
public void SetLoanedState(bool State)
{
isLoaned = State;
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke();
}
NavMenu.razor (change to use service SetLoanedState()
@inject BookService bookService;
@code {
private bool collapseNavMenu = true;
private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;
private void ToggleNavMenu()
{
collapseNavMenu = !collapseNavMenu;
}
private void LoanBookClicked()
{
bookService.SetLoanedState(true);
}
private void ReturnBookClicked()
{
bookService.SetLoanedState(false);
}
}
for more information look at Chris Sainty's blog post here it makes this really clear