Generic Component with Nullable Type

Posted 155 days ago by AAdaris
0

Hello Everyone,

I have this generic Enum Selector Component which works. Is there a way to allow nullable types as well? Thank you so very much for any help! Kind blessings, Andreas

@typeparam T where T : Enum


<MudSelect T="string" @bind-Value="text" @bind-SelectedValues="Items" Dense="true" AnchorOrigin="Origin.BottomCenter" Clearable>
    @foreach (var value in Enum.GetValues(typeof(T)))
    {
        <MudSelectItem Value="value.ToString()">
            <MudChip Size="Size.Small" Class="@($"enum-type-{(int)value}")"
                     Variant="Variant.Filled">@(((T)value).GetDisplayName())</MudChip>
            </MudSelectItem>
    }
</MudSelect>
@code {
    private string text { get; set; }

    private IEnumerable<string> items;
    public IEnumerable<string> Items
    {
        get { return items; }
        set
        {
            items = value;
            if (value.Count() > 0)
            {
                if (Value != null && Value.ToString() != value.First())
                {
                    Value = (T)Enum.Parse(typeof(T), value.First(), true);
                    ValueChanged.InvokeAsync(Value);
                }
            }
        }
    }

    [Parameter]
    public T? Value { get; set; }

    [Parameter]
    public EventCallback<T?> ValueChanged { get; set; }

    protected override void OnInitialized()
    {
        if (Value != null)
        {
            text = Value.ToString();
        }
        Items = new HashSet<string>() { text };
    }
}
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 0
An error has occurred. This application may no longer respond until reloaded. Reload 🗙