|
class="w-75 mt-5 container">
<SfDropDownList TItem="Person" TValue="Colors?" PopupHeight="230px" Placeholder="Race" @bind-Value="@person.FavoriteColor" DataSource="@colors">
<DropDownListFieldSettings Text="Name" Value="FavoriteColor"></DropDownListFieldSettings>
</SfDropDownList>
<h3>@person.FavoriteColor</h3>
</div>
@code{
public Person person { get; set; } = new Person();
public class Person
{
public string Name { get; set; }
public Colors? FavoriteColor { get; set; }
}
public enum Colors
{
[Display(Name = "The Color Red")]
Red,
[Display(Name = "The Color Orange")]
Orange,
[Display(Name = "The Color Green")]
Green,
[Display(Name = "The Color Blue")]
Blue
}
protected override void OnInitialized()
{
person.FavoriteColor = Colors.Orange;
}
public IEnumerable<Person> colors = GetEnumDisplayNames<Colors>();
public static List<Person> GetEnumDisplayNames<T>()
{
var type = typeof(T);
return Enum.GetValues(type)
.Cast<T>()
.Select(x => new Person
{
FavoriteColor = x as Colors?,
Name = type.GetMember(x.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()?.Name ?? x.ToString()
}).ToList();
}
} |
This also works with a Dictionary
<SfDropDownList ID="Type" TItem="KeyValuePair<ProjectType, string>" @bind-Value="@project.Type" TValue="ProjectType?"
DataSource="_types"
FloatLabelType="FloatLabelType.Always" Placeholder="Project type">
<DropDownListFieldSettings Value="Key" Text="Value"></DropDownListFieldSettings>
</SfDropDownList>
public enum ProjectType
{
[Display(Name = "Type 1")]
Type1 = 0,
[Display(Name = "Type 2")]
Type2 = 1
}
private Dictionary<ProjectType, string> _types = EnumExtensions.ToDictionary<ProjectType>();
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enumValue) => enumValue.GetType()
.GetMember(enumValue.ToString())
.FirstOrDefault()?
.GetCustomAttribute<DisplayAttribute>()?
.GetName() ?? string.Empty;
public static Dictionary<T, string> ToDictionary<T>() where T : struct
=> Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => (e as Enum).GetDisplayName());
}
Hi Roberta,
We're delighted to hear that the information was helpful to you and that you were able to resolve the issue. Thank you for sharing the details about the enum working with a dictionary. If you have any further questions or need assistance in the future, please get back to us.
Regards,
Yohapuja S