Component Association
Associate with parent and child component
Parent Component
For .razor
file component, you should create cascading component manually
@inherits BlazorComponentBase
<CascadingValue Value="this">
<ul @attributes="AdditionalAttributes">@ChildContent</ul>
</CascadingValue>
For component class, just define ParentComponent
attribute
[ParentComponent]
public class List : BlazorComponentBase
{
}
Child Component
Define ChildComponent
attribute for child component
@inherits BlazorComponentBase
@attribute [ChildComponent(typeof(List))]
<!--For .NET 7 can use generic attribute-->
@attribute [ChildComponent<List>]
<li @attributes="@AdditionalAttributes">
@ChildContent
</li>
@code{
[CascadingParameter]public List CascadedList { get; set; }
protected override void BuildCssClass(ICssClassBuilder builder)
{
if(CascadedList.Active)
{
//..
}
}
}
[ChildComponent(typeof(List))]
//[ChidlComponent<List>] // for .net7
public class ListItem : BlazorComponentBase
{
[CascadingParameter]public List CascadedList { get; set; }
protected override void BuildCssClass(ICssClassBuilder builder)
{
if(CascadedList.Active)
{
//..
}
}
}
So ListItem
component must be inside of List
component, or an exception will be thrown if ListItem
dose not inside of List
component
<List>
<ListItem>...</ListItem>
</List>
<!--throw exception-->
<ListItem />
Optional
Set true
ignore the exception if not in parent component
@inherits BlazorComponentBase
@attribute [ChildComponent(typeof(List))]
<!--For .NET 7 can use generic attribute-->
@attribute [ChildComponent<List>]
<li @attributes="@AdditionalAttributes">
@ChildContent
</li>
@code{
[CascadingParameter]public List CascadedList { get; set; }
protected override void BuildCssClass(ICssClassBuilder builder)
{
if(CascadedList.Active)
{
//..
}
}
}
[ChildComponent(typeof(List), Optional = true)]
//[ChidlComponent<List>(Optional = true)] // for .net7
public class ListItem : BlazorComponentBase
{
//This instance may be null
[CascadingParameter]public List? CascadedList { get; set; }
protected override void BuildCssClass(ICssClassBuilder builder)
{
if(CascadedList is not null && CascadedList.Active)
{
//..
}
}
}
<!--never throw exception-->
<ListItem />