ASP.NET CORE 6 - Blazor - How can we infer the component type for child components from a method?

Viewed 363

The method which is used is ItemsProvider. Here are the 2 components.

Column.razor

@typeparam TTT

@code {
    [CascadingParameter] public Grid<TTT>? MyGrid { get; set; }

    protected override void OnInitialized()
    {
        MyGrid?.Add(this);
    }
}

Grid.razor

@attribute [CascadingTypeParameter(nameof(TTT))]
@typeparam TTT

<CascadingValue Value="this">
    @Columns
</CascadingValue>

@code {
    [Parameter] public List<TTT>? Items { get; set; }
    [Parameter] public RenderFragment? Columns { get; set; }
    [Parameter] public Func<Task<IEnumerable<TTT>>>? ItemsProvider { get; set; }
    
    private readonly List<Column<TTT>> MyColumns = new();

    public void Add(Column<TTT> column)
    {
        MyColumns.Add(column);
    }
}

When using these 2 components on the Index page below, I got the following error messages:

RZ10001 The type of component 'Column' cannot be inferred based on the values provided.
Consider specifying the type arguments directly using the following attributes: 'TTT'.
CS0411 The type arguments for method 'TypeInference.CreateColumn_1(RenderTreeBuilder, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

<Grid ItemsProvider="@Provide">
    <Columns>
        <Column></Column>
    </Columns>
</Grid>

@code {
    List<Test> tests = new();

    async Task<IEnumerable<Test>> Provide()
    {
        await Task.Delay(1);
        return new List<Test>() { new Test() { Name = "Name" } };
    }
}

The problem can be fixed by:

A) Define the type explicitly for the Column: <Column TTT="Test">
B) Define the Items parameter for the Grid: <Grid ItemsProvider="@Provide" Items="tests">
C) Use the ItemsProvider delegate defined for the official Virtualize component.

Is there another solution that avoids A, B and C?

PS: Column.razor and Grid.razor are in a library.

0 Answers
Related