Bind each value of an enum to a checkbox Blazor

2.1k Views Asked by At

I have an [Flags] Enum that contains some datapoints that I want to collect. My goal is to display and bind each value(each bit) as an individual checkbox for the user to check. However, I do not know how to bind individual values of an Flags enum to a component, nor if it is even possible. To better explain my point:

Say this is my enum:

[Flags]
public enum DataPoints{
     Large = 1,
     Soft  = 2,
     Green = 4,
     Round = 8
}

Then I'd want a property in my form's model of DataPoints type that can hold those values:

//possible data points like:
// 9: Round and Large
// 6: Soft and Green
public DataPoints Data;

I was thinking something like the following but I don't think you can bind individual values/bits of an enum to a component like that:

@foreach (DataPoints datum in Enum.GetValues(typeof(DataPoints)))
   {
      <CheckBox @bind-Value="what? Data.datum?"></CheckBox>
   }
2

There are 2 best solutions below

5
Bennyboy1973 On BEST ANSWER

Something I find myself doing a LOT in Blazor is making what I call carrier classes, especially for selecting items. I use the same technique to select images from a list, answers from a multiple choice question, and so on.

@foreach (var item in CheckableEnums)
{
    <span> @item.DataPoint.ToString() &nbsp;</span>
    <input type="checkbox" @bind="item.IsSelected" />
    <br />
}
<br />
@{ SumValue = (DataPoints)(CheckableEnums.Where(cb => cb.IsSelected).Select(val => (int)val.DataPoint)).Sum(); }
<span>Selected Flags: </span>@SumValue.ToString()

@code {
    [Flags]
    public enum DataPoints
    {
        Large = 1,
        Soft = 2,
        Green = 4,
        Round = 8
    }
    class CheckableEnum
    {
        public DataPoints DataPoint { get; set; }
        public bool IsSelected;
    }
    DataPoints SumValue { get; set; }
    List<CheckableEnum> CheckableEnums { get; set; } = new List<CheckableEnum>();
    protected override void OnInitialized()
    {
        foreach (var DPvalue in Enum.GetValues(typeof(DataPoints)))
            CheckableEnums.Add(new CheckableEnum() { DataPoint = (DataPoints)DPvalue });
    }
}

-edit- The previous fiddle was broken so: https://blazorfiddle.com/s/t523591k

0
Bennyboy1973 On

Since my first answer is already accepted, I didn't want to change it. But JHBonarius' suggestion to use .Aggregate() is better if there are any combination Flags:

In markup:

@{ SumValue = CheckableEnums.Where(cb => cb.IsSelected).Select(val => val.DataPoint).Aggregate((DataPoints)0,(result, value) => result | value); }

and modified test flags:

@code {
    [Flags]
    public enum DataPoints
    {
        Large = 1,
        Soft = 2,
        Green = 4,
        Round = 8,

        LargeAndSoft = 3 // Added value.
    }
}

Fiddle: https://blazorfiddle.com/s/hu9kooon