Cascading values by name

Specifying a value for a cascading parameter is very simple. At any point in our Razor HTML mark-up we can create a CascadingValue element. Everything rendered within that element will have access to the value specified.

@page "/"

<h1>Toggle the options</h1>
<input @bind-value=firstOptionValue type="checkbox" /> first option
<br />
<input @bind-value=secondOptionValue type="checkbox" /> second option
<br />

<CascadingValue Name="FirstOption" [email protected]>
	<CascadingValue Name="SecondOption" [email protected]>
		<FirstLevelComponent />
	</CascadingValue>
</CascadingValue>

@code {
	bool firstOptionValue;
	bool secondOptionValue;
}

Consuming the value is just as simple. Any component, no matter how deeply nested it is inside the CascadingValue element, can access the value with a property decorated with the CascadingParameter attribute.

<ul>
	<li>FirstOption = @FirstOption</li>
	<li>SecondOption = @SecondOption</li>
</ul>

@code {
	[CascadingParameter(Name="FirstOption")]
	public bool FirstOption { get; set; }

	[CascadingParameter(Name="SecondOption")]
	public bool SecondOption { get; set; }
}

Note that the name of our property that consumes the value is irrelevant. Blazor will not look for a property with the same name specified in the CascadingValue element; we are free to name our property anything we like, it’s actually the Name on the CascadingParameterAttribute that identifies which cascading value should be injected.