I have a Blazor component "Table" with a RenderFragment parameter "TableHeader", containing a collection of TableHeaderColumn elements. This is an example usage of the Table component:
<Table Items="@Persons">
<TableHeader>
<TableHeaderColumn Label="First Name" />
<TableHeaderColumn Label="Last Name" />
</TableHeader>
<TableRow>
......
</TableRow>
</Table>
Using CascadingValue, I want to pass the Table instance to all TableHeaderColumn instances in the "TableHeader" render fragment, but I cannot get this to work for some reason.
My theory is that this is not possible as long as Table component is using a TItem typeparam, while TableHeaderColumn component is not.
This is the Table.razor file:
@typeparam TItem
@inherits TableBase<TItem>
<table>
<thead>
<tr>
<CascadingValue Value="this">
@TableHeader
</CascadingValue>
</tr>
</thead>
<tbody>
....
</tbody>
</table>
TableBase.cs:
public class TableBase<TItem>
{
[Parameter]
public RenderFragment TableHeader { get; set; }
[Parameter]
public RenderFragment<TItem> TableRow { get; set; }
}
public class TableHeaderColumnBase
{
[CascadingParameter]
public Table<object> Table { get; set; }
}
As you can see, since the TableHeaderColumn component is not using a typeparam, I am using "object" as Table type. Not sure if this is the right approach.
The cascading parameter in TableHeaderColumnBase does not get populated and I am not sure how I can get this to work.
If I pass one of the properties on the Table-instance instead, like "this.Title", it works fine.
Anyone knows what I am missing or if this is even possible to do?
You need to pass the TItem element to the TableHeaderColumnBase component
<Table Items="@Persons">
<TableHeader>
<TableHeaderColumn TItem="Person" Label="First Name" />
<TableHeaderColumn TItem="Person" Label="Last Name" />
</TableHeader>
<TableRow>
......
</TableRow>
In the TableHeaderColumn.razor file, add a parameter
[CascadingParameter] public Table<TItem> ParentTable { get; set; }
and @typeparam TItem at the top.
You can now call all the methods and access the variables of the parent component and use the TItem as you whish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With