Blazor - razor page not updating after property from DI Service is changed

前端 未结 2 1412
刺人心
刺人心 2021-01-05 20:28

Using dotnet 3.1.100-preview2-014569

Ok consider the following example:

Create a new Blazor WebAssemply project from template, then add the following:

<
2条回答
  •  天命终不由人
    2021-01-05 20:40

    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

提交回复
热议问题