Search code examples
c#asp.net-coreblazor

Blazor bind to update UI when callback changes property


Using Blazor, how can the displayed text update when the Result property is modified by the callback function?

<p>The current value is: @Result </p>

@code {
    private string Result { get; set; } = "";

    protected override void OnInitialized()
    {
        OtherCode.OnResultChangedCB += (string? newResult) => Result = newResult ?? "None";
        base.OnInitialized();
    }
}

Solution

  • If the calback is from a backend process, the handler will not be invoked through the IHandleEvent handler defined by ComponentBase. You need to call StateHasChanged in the handler.

    Depending on the lifecycle of the caller, you may also need to remove the registration when the component is destroyed.

    @implements IDisposable
    @code {
        private string Result { get; set; } = "";
    
        protected override void OnInitialized()
        {
            OtherCode.OnResultChangedCB += this.OnResultChanged;
            base.OnInitialized();
        }
    
        private void OnResultChanged(string? result)
        {
                Result = newResult ?? "None";
                // May be called outsode the Synchronisation Context so switch back
                InvokeAsync(StateHasChanged);  
        }
    
        public Void Dispose()
            {
                OtherCode.OnResultChangedCB -= this.OnResultChanged;
            }
    }
    

    Note : If this is Net8 make sure the page is Interactive.