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

前端 未结 2 1419
刺人心
刺人心 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:44

    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));
                }
            }
        }
    

    Books.razor

    @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(); } }

    NavMenu.razor

    @code {
    
        // Code removed for brevity
    
        private void LoanBookClicked()
        {
            bookService.IsLoaned = true;      
        }
        private void ReturnBookClicked()
        {
            bookService.IsLoaned = false;      
        }
    }
    

    Hope this works...

提交回复
热议问题