Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CascadingValueSource

Tags:

blazor

Has anyone figured out how to interactively use a CascadingValueSource.

The documention shows:

builder.Services.AddCascadingValue(sp =>
{
    var daleks = new Daleks { Units = 789 };
    var source = new CascadingValueSource<Daleks>(daleks, isFixed: false);
    return source;
});

How do you get a reference to the CascadingValueSource to call NotifyChangedAsync?

I'm probably having a senior moment, but you're only in the builder at this point, so you can't get to any services you define.

like image 715
MrC aka Shaun Curtis Avatar asked Jun 29 '26 19:06

MrC aka Shaun Curtis


1 Answers

You can register the cascaded value like so

builder.Services.AddScoped((sp) =>
{
    var daleks = new Daleks { Units = 789 };
    return new CascadingValueSource<Daleks>(daleks, isFixed: false);
});

builder.Services.AddCascadingValue(sp => sp.GetRequiredService<CascadingValueSource<Daleks>>());

With that you can then create a dependency on CascadingValueSource in a component or in a service thats used by a component:

@inject CascadingValueSource<Daleks> source

<button @onclick="OnButtonClick">Notify</button>

@code {
    protected Task OnButtonClick() => source.NotifyChangedAsync();
}

Of course, this example doesn't make much sense. But it shows how you can get the source.

like image 57
Sam Avatar answered Jul 03 '26 06:07

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!