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>
}
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() </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