Home > Software engineering >  MudBlazor - Generic MudTable
MudBlazor - Generic MudTable

Time:12-21

I am trying to create my own custom component that inherits from MudTable. In my custom component I have created an IEnumerable property that has a type of TItem, and then i send a DataSource from the parent class and i also define the TItem type via parameter. The problem I have is that MudTable uses @context to get the values from the DataSource which is known when you give the DataSource with a predefined type. You can see here MudTable.

But how can i do that when the DataSource is a generic type, the @context does not know in which property to take the value from.

Parent component which includes the Custom Component:

<CETable DataSource="Persons" ItemType="Person"></CETable>

public List<Person> Persons { get; set; }

protected override void OnInitialized()
{
    Persons = new List<Person>();
    Persons.Add(new Person { AgeOfPerson = "25", Name = "Mike" });
    Persons.Add(new Person { AgeOfPerson = "35", Name = "John" });
    Persons.Add(new Person { AgeOfPerson = "45", Name = "Michel" });

}

public class Person
{
    public string Name { get; set; }
    public string AgeOfPerson { get; set; }

}

Custom Component (CETable):

@typeparam ItemType
@inherits MudTable<ItemType>
<MudTable Items="DataSource">
<HeaderContent>
 @*I will send later those columns as a parameter*@

    <MudTh>Name</MudTh>
    <MudTh>AgeOfPerson</MudTh>

</HeaderContent>
<RowTemplate>
    <MudTd DataLabel="Name">@context.</MudTd> // How To define the context here ?
    <MudTd DataLabel="AgeOfPerson">@context.</MudTd> // How To define the context here ?
</RowTemplate>
</MudTable>
@code{
[Parameter]
public IEnumerable<ItemType> DataSource { get; set; }
}

Thank you for the help.

CodePudding user response:

i found a solution. I will post it here in case anyone needs it. Basically, i am creating a render fragment which takes the content from the parent component and sets the value in the child component.

Parent component which includes the Custom Component:

<CETable DataSource="Persons" ItemType="Person">
<CEHeaderTemplate>
    <CETh>Name</CETh>
    <CETh>AgeOfPerson</CETh>
</CEHeaderTemplate>
<CERowTemplate>
    <CETd DataLabel="Name">@context.Name</CETd>
    <CETd DataLabel="AgeOfPerson">@context.AgeOfPerson</CETd>
</CERowTemplate></CETable>

Custom Component (CETable):

@typeparam ItemType
@inherits MudTable<ItemType>
<MudTable Items="DataSource">
<HeaderContent>
    @CEHeaderTemplate
</HeaderContent>
<RowTemplate>
    @CERowTemplate(@context)
</RowTemplate></MudTable>

@code{
[Parameter]
public IEnumerable<ItemType> DataSource { get; set; }

[Parameter]
public RenderFragment<ItemType> CERowTemplate { get; set; }

[Parameter]
public RenderFragment CEHeaderTemplate { get; set; }
}
  • Related