简体   繁体   中英

Is there a way to set a generic type to a Blazor component at runtime?

<GenericInputFor> provides markup based on the argument it receives and its type, it behaves fine with compile time types, but when I try to iterate through some class properties with reflection it says that the type cannot be inferred :

 @foreach (var property in typeof(SomeClass).GetProperties())
        {
           <GenericInputFor Model="property.GetValue(in2,null)" ModelChanged="@((ChangeEventArgs __e) => property.SetValue(in2, __e.Value))"></GenericInputFor>
        }

@code {
    public SomeClass in2 { get; set; }

    protected override void OnInitialized()
    {
        in2 = new SomeClass();
        base.OnInitialized();
    }
}

I have seen multiple awesome solutions like Setting generic type at runtime and Creating a Generic type instance with a variable containing the Type but I couldn't apply it to blazor components.

You should try setting the TItem attribute on the element:

@foreach (var property in typeof(SomeClass).GetProperties())
{
    <GenericInputFor TItem="typeof(SomeClass)" Model="property.GetValue(in2,null)" ModelChanged="@((ChangeEventArgs __e) => property.SetValue(in2, __e.Value))"></GenericInputFor>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM