bale3
bale3

Reputation: 383

Pass complex type with typeparam to child RenderFragment as CascadeParameter

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?

Upvotes: 3

Views: 1529

Answers (1)

Francesco Cristallo
Francesco Cristallo

Reputation: 3073

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.

Upvotes: 1

Related Questions