Blog


INotifyPropertyChanged

4/5/2022

By: Shaun Walker

One of the most common questions asked by new Blazor developers is how do you communicate between components? Essentially this question boils down to "state management"... and the answer is that it depends on what you are trying to accomplish as there are many different solutions to consider, each catering to different UI scenarios. As a proof point, Oqtane actually takes advantage of three different solutions for state management within the framework - EventCallbacks, Cascading Parameters, and State Containers and if you examine the source code you will be able to see each of them in action.

In Oqtane 3.1 the framework has been enhanced with a new state management technique which piggbacks on top of the State Container concept. This is a feature which has existed for a long time in many different UI frameworks from Microsoft over the years - INotifyPropertyChanged.

INotifyPropertyChanged is an interface which allows a component to subscribe to a property changed event that was published by another component. Oqtane exposes this capability through its SiteState service which is already registered and available in all components. A new generic "Properties" property has been added to SiteState which allows developers to dynamically specify property values that can be passed to other components for consumption.

Publisher component

@inject SiteState SiteState

@code{
    protected override void OnInitialized()
    {
        SiteState.Properties.MyProperty = true;
    }
}

Subscriber component

@inject SiteState SiteState
@using System.ComponentModel
@implements IDisposable

@code{
    private bool MyProperty;

    protected override void OnInitialized()
    {
        ((INotifyPropertyChanged)SiteState.Properties).PropertyChanged += PropertyChanged;
    }

    private void PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(MyProperty))
        {
            MyProperty = SiteState.Properties.MyProperty;
            StateHasChanged();
        }
    }

    public void Dispose()
    {
        ((INotifyPropertyChanged)SiteState.Properties).PropertyChanged -= PropertyChanged;
    }
}


Do You Want To Be Notified When Blogs Are Published?
RSS


An error has occurred. This application may no longer respond until reloaded. Reload 🗙