C# Blazor: How to use @typeparam in Code behind? (with workaround)

▼魔方 西西 提交于 2020-04-13 03:56:08

问题


In a Blazor .razor file you can use @typeparam MyType to use generic parameters. For example:

MyComponent.razor

@typeparam MyType

<SomeHtml />

@code
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

So you can call:

<MyComponent MyType="MyTypeABC" MyList="@MyData.MyList" />

But I prefer code behind (razor.cs), how can I use a parameter for type like @typeparam MyType in the razor.cs file?

My current workaround is:

MyComponent.razor

@inherits MyComponentCode<MyType>
@typeparam MyType

MyComponent.razor.cs

public class MyComponentCode<MyType> : ComponentBase
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

I miss something like [TypeParameter], but maybe there are better solutions, any ideas? Or maybe it's a general question about "how to use razor @statements in a code behind".


Update from 2020-02-27:

With suggestion from Roger Wolf (see below), a bit better way:

MyComponent.razor

@typeparam MyType

MyComponent.razor.cs

public class MyComponent
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

Call

<MyComponent MyType="MyTypeABC" />

回答1:


You were pretty close, just need to add partial to the class definition:

using Microsoft.AspNetCore.Components;

namespace BlazorApp1.Components
{
    public partial class MyCustomComponent<T> : ComponentBase
    {
        [Parameter]
        public string Label { get; set; }
    }
}

The Razor part:

@namespace BlazorApp1.Components
@typeparam T

<label>@($"{Label}. Provided type is {typeof(T).Name.ToUpper()}")</label>

The usage (Index.razor):

@page "/"
@using BlazorApp1.Components

<MyCustomComponent T="long" Label="Custom component label" />

This way, you wouldn't need inheriting your component from it, as both become parts of the same class.



来源:https://stackoverflow.com/questions/60393496/c-sharp-blazor-how-to-use-typeparam-in-code-behind-with-workaround

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!