In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.
Parameters flow down on every parent render
- Parent
Homerenders its markup<ItemList Title="Ingredients" Items="ingredients" InitialLimit="3"> - The child's
SetParametersAsyncrunseach value goes into the matching[Parameter]property OnInitializedonce,OnParametersSeteach timeItemListcopiesInitialLimitinto privatelimitonly once- The child changes its own stateShow all sets
limit;Spoilerwrites its ownOpenparameter Homerenders againlist and fragment parameters can't be compared, so all are assigned again- Private
limitsurvives,Openis resetthe list still shows 5 items; the spoiler is closed again
A parameter belongs to the parent and is assigned again when the parent renders. Keep the child's own state in a private field, or report changes up with an EventCallback.
Parameters are properties the parent sets
A component parameter is a public property with the [Parameter] attribute. A parent sets it by writing an attribute with the same name on the component's tag. In this lesson's project, Home writes <ItemList Title="Ingredients" Items="ingredients" InitialLimit="3">. The Razor compiler checks those names against the ItemList class at build time. For a parameter that is not a string, the attribute value is a C# expression, which is why Items="ingredients" passes the field and InitialLimit="3" passes the integer 3.
Under the hood, Home's generated BuildRenderTree records a component entry for ItemList with one value per attribute. When the renderer processes that entry, it calls the child's SetParametersAsync with a ParameterView holding the values. The ComponentBase implementation assigns each value to the matching property, calls OnInitialized the first time, calls OnParametersSet every time, and then renders the child. Keep parameter properties as plain auto-properties. Code in a parameter's setter runs during this assignment, at moments you do not control.
Required parameters and default values
A parameter the parent does not set keeps whatever value the property already had. That is why ItemList gives InitialLimit a default of 3 and declares ChildContent as nullable: both are optional. Title, Items and ItemTemplate carry [EditorRequired]. When a parent leaves one out, the Razor compiler reports warning RZ2012, for example "Component 'ItemList' expects a value for the parameter 'Title', but a value may not have been provided." SharpRune shows the same warning when it builds the project.
[EditorRequired] is only a build-time check. Nothing stops a parent from passing null on purpose, and nothing checks the attribute when a component is created from code, for example with DynamicComponent. That is why the properties still start with safe values: an empty string for Title and an empty list for Items. With nullable reference types on, ItemTemplate is initialized with default!, which is a promise to the compiler that a parent will always supply it. Make that promise only for parameters that also carry [EditorRequired].
ChildContent and RenderFragment<T> templates
A RenderFragment is a delegate that writes part of a render tree. When a component has a RenderFragment parameter named ChildContent, the markup between its opening and closing tags is compiled into that delegate. Spoiler in this project receives its answer text that way. The child decides where the content appears by writing @ChildContent in its own markup. The markup inside a fragment is compiled into the parent's class, so it can use the parent's fields, while the child decides where and whether it appears.
RenderFragment<T> is a delegate that takes a value and returns a RenderFragment. ItemList uses it for ItemTemplate: the parent writes the markup for one item, and the child calls @ItemTemplate(item) inside its loop. Inside the template the item is available as context, or under the name you choose with the Context attribute, as Home does with Context="ingredient". Once you pass more than one fragment, write each one as a child element named after its parameter, including <ChildContent>. The @typeparam TItem directive makes ItemList generic. The compiler infers TItem from the Items attribute, so the ingredient list is an ItemList<Ingredient> and the steps list is an ItemList<string>.
Why a child must not write to its own parameter
A parameter belongs to the parent. Each time the parent renders, Blazor decides whether the child might have new values. For a small set of known types, such as strings, numbers and booleans, it compares old and new values and skips the child if nothing changed. For other types, including RenderFragment and lists, it cannot tell, so it calls SetParametersAsync on the child again and assigns every parameter the parent passes.
Spoiler has a bool Open parameter and a ChildContent fragment. Its Toggle method sets Open to true, and the answer appears. When you tap Render Home again, Home renders, the fragment makes Blazor update the child, and Open receives the parent's value, false. The answer disappears. ItemList also receives fresh parameters on that render, but its Show all state lives in a private field named limit that only the child assigns. OnInitialized copies InitialLimit into limit once, so later assignments never reset it.
The bug can hide for a long time. A child with only simple parameters may keep an overwritten value, because Blazor skips it while the parent's values stay the same. Then someone adds a fragment or a list parameter, or the parent changes one value, and the child resets without warning. If the parent needs to know about the change or control it, let the parent own the value and have the child report changes through a callback. Lesson 3 covers that pattern.
Common mistakes
Writing to a parameter from inside the child is the mistake this lesson demonstrates, and it is hard to spot because the code works until the parent renders. A related mistake is changing the contents of a list the parent passed in. The list is the parent's object, so adding or removing items from the child changes the parent's data behind its back.
Other problems come up often. A [Parameter] property that is not public builds, but the app fails at run time with "Parameters must be public" as soon as a parent sets it. [Parameter] on a field does not compile, because the attribute only applies to properties. A fragment parameter named Content or Body does not receive the markup between the tags; only ChildContent does. Two nested templates that both use the default name context make the compiler report an error, and the fix is a distinct Context name for each.
Practice and review
Remove Title="Steps" from Home.razor, build, and read the RZ2012 warning; then put it back. Add Context="step" to the steps template and use that name. Give ItemList an optional EmptyContent fragment that renders when Items is empty, and pass an empty list to see it. Fix Spoiler the way ItemList works: rename the parameter to InitiallyOpen, copy it into a private field in OnInitialized, and confirm that Render Home again no longer closes it. Finally, in a copy of the broken Spoiler, replace ChildContent with a string parameter named Answer and check whether the overwrite still happens. The change detection rules above explain the result.
[Parameter]marks a public property that the parent sets with an attribute of the same name.[EditorRequired]produces warning RZ2012 at build time; it checks nothing at run time.ChildContentreceives the markup between the tags; aRenderFragment<T>template receives one item at a time as context.- A parent render may assign every parameter again, so a child keeps its own state in private fields.
Parameters and child content — Blazor WebAssembly project
Run the project
- Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
- Tap Show all 5 under Ingredients and Show answer under the question. Then tap Render Home again and compare the two.
- Change a .razor file and tap Run again to rebuild.
- On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.
Project files
ComponentParameters.csproj
Download file ↗<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>ComponentParameters</AssemblyName>
<RootNamespace>ComponentParameters</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
</ItemGroup>
</Project>
Program.cs
Download file ↗using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using ComponentParameters;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// <App> replaces <div id="app"> in wwwroot/index.html.
builder.RootComponents.Add<App>("#app");
// HeadOutlet lets <PageTitle> set the browser tab title.
builder.RootComponents.Add<HeadOutlet>("head::after");
await builder.Build().RunAsync();
App.razor
Download file ↗<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<h1>Not found</h1>
<p>There is no page at this address.</p>
</NotFound>
</Router>
_Imports.razor
Download file ↗@using System.Net.Http
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using ComponentParameters
@using ComponentParameters.Components
Pages/Home.razor
Download file ↗@page "/"
<PageTitle>Pancakes</PageTitle>
<h1>Pancakes</h1>
@* Each attribute sets a parameter of ItemList. TItem is inferred from Items: Ingredient.
Because ItemTemplate is written as an element, the other content goes in <ChildContent>. *@
<ItemList Title="Ingredients" Items="ingredients" InitialLimit="3">
<ChildContent>
<p class="muted">Enough for about eight pancakes.</p>
</ChildContent>
<ItemTemplate Context="ingredient">
<span>@ingredient.Name</span>
<span class="muted">@ingredient.Amount</span>
</ItemTemplate>
</ItemList>
@* The same component with TItem = string. Without Context="...", the item is called context. *@
<ItemList Title="Steps" Items="steps" InitialLimit="2">
<ItemTemplate>@context</ItemTemplate>
</ItemList>
@* Content between the tags becomes the Spoiler's ChildContent. *@
<Spoiler Question="Why let the batter rest?" Open="false">
The flour soaks up the milk, so the batter thickens and the pancakes come out softer.
</Spoiler>
<section class="card">
<h2>Render the parent again</h2>
<p>Open the answer above and tap <strong>Show all 5</strong> in Ingredients. Then tap this button. Home renders again and passes its parameter values to every child once more.</p>
<div class="row">
<button class="primary" @onclick="() => taps++">Render Home again</button>
</div>
<p class="muted">Taps: @taps</p>
</section>
@code {
private int taps;
private readonly List<Ingredient> ingredients =
[
new("Flour", "200 g"),
new("Milk", "300 ml"),
new("Eggs", "2"),
new("Sugar", "1 tbsp"),
new("Salt", "1 pinch"),
];
private readonly List<string> steps =
[
"Whisk the eggs, milk and sugar.",
"Stir in the flour and salt.",
"Let the batter rest for 10 minutes.",
"Fry in a hot pan, about a minute per side.",
];
public sealed record Ingredient(string Name, string Amount);
}
Components/ItemList.razor
Download file ↗@* @typeparam makes this a generic component: ItemList<TItem>. *@
@typeparam TItem
<section class="card">
<h2>@Title</h2>
@ChildContent
<ul class="items">
@foreach (var item in Items.Take(limit))
{
@* ItemTemplate is a RenderFragment<TItem>: call it with one item to get that item's markup. *@
<li>@ItemTemplate(item)</li>
}
</ul>
@if (Items.Count > InitialLimit)
{
<button class="link" @onclick="ToggleAll">@(limit < Items.Count ? $"Show all {Items.Count}" : "Show fewer")</button>
}
</section>
@code {
// [EditorRequired]: the Razor compiler warns (RZ2012) when a parent leaves this out.
[Parameter, EditorRequired] public string Title { get; set; } = "";
[Parameter, EditorRequired] public IReadOnlyList<TItem> Items { get; set; } = [];
// A template: markup written by the parent, filled in once per item by this component.
[Parameter, EditorRequired] public RenderFragment<TItem> ItemTemplate { get; set; } = default!;
// Optional content from the parent, shown under the title.
[Parameter] public RenderFragment? ChildContent { get; set; }
[Parameter] public int InitialLimit { get; set; } = 3;
// This component's own state. The parent never assigns it, so a parent render cannot reset it.
private int limit;
// Runs once, when the component is created: copy the starting value from the parameter.
protected override void OnInitialized() => limit = InitialLimit;
private void ToggleAll() => limit = limit < Items.Count ? Items.Count : InitialLimit;
}
Components/Spoiler.razor
Download file ↗@* Written the wrong way on purpose: Toggle writes to the Open parameter. *@
<section class="card spoiler">
<h2>@Question</h2>
@if (Open)
{
<p>@ChildContent</p>
}
<button class="link" @onclick="Toggle">@(Open ? "Hide answer" : "Show answer")</button>
</section>
@code {
[Parameter, EditorRequired] public string Question { get; set; } = "";
[Parameter] public bool Open { get; set; }
[Parameter] public RenderFragment? ChildContent { get; set; }
// Wrong: Open belongs to the parent. When the parent renders again, Blazor assigns the
// parent's value (false) to Open once more, and this change is lost. ItemList shows the
// fix: keep the state in a private field and only read the parameter as a starting value.
private void Toggle() => Open = !Open;
}
wwwroot/index.html
Download file ↗<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Pancakes</title>
<base href="/" />
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="ComponentParameters.styles.css" />
</head>
<body>
<div id="app">
<p class="loading">Starting .NET…</p>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">✕</span>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.css
Download file ↗:root {
color-scheme: light dark;
--accent: #6b4eff;
--line: #d8d6e4;
--muted: #777;
}
body {
margin: 0;
font-family: -apple-system, system-ui, sans-serif;
line-height: 1.5;
}
#app {
max-width: 720px;
margin: 0 auto;
padding: 20px 16px 40px;
box-sizing: border-box;
}
a, button, input, label {
touch-action: manipulation;
}
h1 {
font-size: 1.8rem;
margin: 0 0 12px;
}
h1:focus {
outline: none;
}
h2 {
font-size: 1.15rem;
margin: 0 0 8px;
}
.loading {
padding: 32px 16px;
color: var(--muted);
}
.row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
input:not([type=checkbox]), select {
font: inherit;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
min-width: 0;
background: transparent;
color: inherit;
}
button {
font: inherit;
padding: 8px 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: transparent;
color: inherit;
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
button:disabled {
opacity: 0.45;
}
button.link {
border: none;
color: var(--accent);
padding: 4px 6px;
}
.muted {
color: var(--muted);
}
.card {
border: 1px solid var(--line);
border-radius: 12px;
padding: 14px 16px;
margin: 16px 0;
}
.card > :last-child {
margin-bottom: 0;
}
code {
font-family: ui-monospace, Menlo, monospace;
font-size: 0.9em;
overflow-wrap: anywhere;
}
.items {
list-style: none;
padding: 0;
margin: 8px 0;
}
.items li {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 8px 0;
border-bottom: 1px solid var(--line);
}
.spoiler {
border-style: dashed;
}
#blazor-error-ui {
display: none;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px 16px;
background: #ffe8a3;
color: #222;
}
Expected result
Ingredients starts with three rows and a Show all 5 link; Steps starts with two rows and Show all 4. Show all 5 adds Sugar and Salt and changes the link to Show fewer. Show answer reveals the sentence about resting the batter. After Render Home again the tap counter goes up, the ingredient list stays fully open, and the spoiler closes, because Home assigned Open="false" to it once more.
The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.
C# companion practice
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
// RenderFragment<T> has the shape "one T in, markup out". Here the output is a string.
Func<Ingredient, string> row = item => $"{item.Name} ({item.Amount})";
var ingredients = new List<Ingredient>
{
new("Flour", "200 g"), new("Milk", "300 ml"), new("Eggs", "2"), new("Sugar", "1 tbsp"), new("Salt", "1 pinch"),
};
var list = new ItemListModel<Ingredient>();
var spoiler = new SpoilerModel();
ParentRenders();
Show("First render");
list.ToggleAll(); // the list changes its own private field
spoiler.Toggle(); // the spoiler writes to its parameter
Show("After tapping Show all and Show answer");
ParentRenders(); // the parent renders again and assigns its parameter values again
Show("After the parent renders again");
// What a parent render means for a child: every parameter the parent passes is assigned again.
void ParentRenders()
{
list.SetParameters(ingredients, row, initialLimit: 3);
spoiler.SetParameters(open: false);
}
void Show(string label)
{
Console.WriteLine(label);
Console.WriteLine(" list: " + string.Join(", ", list.Visible()));
Console.WriteLine(" spoiler open: " + spoiler.Open);
}
sealed record Ingredient(string Name, string Amount);
sealed class ItemListModel<TItem>
{
public IReadOnlyList<TItem> Items { get; private set; } = [];
public Func<TItem, string> Template { get; private set; } = _ => "";
public int InitialLimit { get; private set; }
private int limit;
private bool initialized;
public void SetParameters(IReadOnlyList<TItem> items, Func<TItem, string> template, int initialLimit)
{
Items = items;
Template = template;
InitialLimit = initialLimit;
if (!initialized)
{
limit = initialLimit; // like OnInitialized: runs only for the first set of parameters
initialized = true;
}
}
public void ToggleAll() => limit = limit < Items.Count ? Items.Count : InitialLimit;
public IEnumerable<string> Visible() => Items.Take(limit).Select(Template);
}
sealed class SpoilerModel
{
public bool Open { get; private set; }
public void SetParameters(bool open) => Open = open;
public void Toggle() => Open = !Open; // the mistake: the parent owns Open
}
C# practice output
First render list: Flour (200 g), Milk (300 ml), Eggs (2) spoiler open: False After tapping Show all and Show answer list: Flour (200 g), Milk (300 ml), Eggs (2), Sugar (1 tbsp), Salt (1 pinch) spoiler open: True After the parent renders again list: Flour (200 g), Milk (300 ml), Eggs (2), Sugar (1 tbsp), Salt (1 pinch) spoiler open: False
If a child's change disappears when the parent renders, the child wrote to its own parameter. Keep that state in a private field, or let the parent own it.