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 partial class MyComponent<MyType>
{
[Parameter]
public List<MyType> MyList{ get; set; }
}
Call
<MyComponent MyType="MyTypeABC" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With