Set and display Blazor view component from class property

459 views Asked by At

I am trying to render different pages based on a class property in blazor with only 1 tagg.

In WPF i was able to create multiple views and specify in the prop of an object which view to render with the UserControl class.

WPF Datacontext:

public UserControl DetailView { get; set; }

WPF parentView:

<UserControl Content="{Binding DetailView}"></UserControl>

This way i was able to dynamicly render diffrent pages based on the property.

I am trying to achieve the same thing in Blazor. I don't want to use a bunch of If elses in my blazorView

2

There are 2 answers

0
Dimitris Maragkos On

I think DynamicComponent is what you are looking for.

Documentation:

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent?view=aspnetcore-6.0

Example of using a select element to dynamically choose which component should be rendered:

<select @bind="selectedComponentIndex">
    @for (var i = 0; i < componentTypes.Count; i++)
    {
        <option value="@i">@componentTypes[i].Name</option>
    }
</select>

<DynamicComponent Type="componentTypes[selectedComponentIndex]" />

@code {
    private int selectedComponentIndex = 0;

    private List<Type> componentTypes = new List<Type>
    {
        typeof(Component1),
        typeof(Component2),
        typeof(Component3),
    };
}
0
hazib On

You are looking for DynamicComponent as @Dimitris Maragkos mentioned.

In my example the views are razor components. Also PropertyViewModel is the parent of the BooleanViewModel, NumberViewModel and TextViewModel.

<div>
    @if(selectedType is not null)
    {
        <div>
            <DynamicComponent Type="@selectedType" />
        </div>
    }
</div>

@code {
    [Parameter]
    public PropertyViewModel PropertyViewModel { get; set; }

    private Type? selectedType;

    protected override void OnInitialized()
    {
        if (PropertyViewModel is BooleanViewModel)
        {
            selectedType = typeof(BooleanView);
        }

        if (PropertyViewModel is NumberViewModel)
        {
            selectedType = typeof(NumberView);
        }

        if (PropertyViewModel is TextViewModel)
        {
            selectedType = typeof(TextView);
        }
    }
}