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

后端 未结 1 1734
情深已故
情深已故 2021-01-17 10:23

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

MyComponent.razo

相关标签:
1条回答
  • 2021-01-17 11:15

    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.

    0 讨论(0)
提交回复
热议问题