blazormudblazormudselect

MudBlazor: Display customized text in Muti-select


I'm trying to display customized text in multi-select of MudBlazor. Everything is fine but the text displayed is "IndicatorDefinition" rather than the customized text.

A quick look of code:

<MudSelect Margin="Margin.Dense" T="IndicatorDefinition" MultiSelection="true"
            SelectAll="true" SelectAllText="Select All"
        @bind-SelectedValues="_selectedIndicators"
        Style="width: 100px;" Clearable="true">
    @foreach (var indicatorDefinition in IndicatorDefinitions)
    {
        <MudSelectItem Value="@indicatorDefinition">@indicatorDefinition.SubTitle</MudSelectItem>
    }
</MudSelect>

@code {
    public string Text {
        get{
            return $"{_selectedIndicators.Count()}/{IndicatorDefinitions.Count()} selected.";
        }
        set { var _ = value;}
    } 
    public List<IndicatorDefinition> IndicatorDefinitions { get; set; } = new()
        {
        new () {SubTitle= "First"}, 
        new () {SubTitle= "Second"}
        };
    public IEnumerable<IndicatorDefinition> _selectedIndicators = new List<IndicatorDefinition>();

    public class IndicatorDefinition
    {
        public string SubTitle { get; set; }
        public double Value { get; set; }
    }
}

Sandbox here: https://try.mudblazor.com/snippet/wYQHaiuJGgaBWuxA

Reference of select here: https://www.mudblazor.com/components/select#variants

I think it's because the T is "IndicatorDefinition" rather than string. I thought of a way, which is:

  1. Use T = "string" instead
  2. Save selected value in List
  3. Rebuild _selectedItems from List.

But it's not elegant.

Thanks all.


Solution

  • You can use the ToStringFunc func delegate.

    Defines how values are displayed in the drop-down list , from docs

    <MudSelect Margin="Margin.Dense" T="IndicatorDefinition" MultiSelection="true"
            SelectAll="true" SelectAllText="Select All"
            @bind-SelectedValues="_selectedIndicators"
            Style="width: 100px;" Clearable="true" 
            ToStringFunc="@(e => e.SubTitle)">
        @foreach (var indicatorDefinition in IndicatorDefinitions)
        {
            <MudSelectItem Value="@indicatorDefinition">@indicatorDefinition.SubTitle</MudSelectItem>
        }
    </MudSelect>