英文:
description attribute in c# shows the description and the value from enum
问题
I want it to show only the text that is within the description area, how can I do that? Thanks!
我希望它只显示在描述区域内的文本,我该如何做到?谢谢!
英文:
Im trying to present a description of enum and it presents me the description and the value.
i want it to show only the text that is within the description area, how can i do that? thanks!
this is the enum:
[Description("Choclate Bar")] choclateBar,
[Description("Caffe Protein Bar")] CafeProteinBar,
[Description("Vanilla Cookie")] vanillaCookie,
this is the code im using to present the enums in a combobox
enter image description here
and the second picture is how its shows.
enter image description here
i want it to show in the combobox the values that within the description ("Choclate Bar", ...)
答案1
得分: 1
以下是您要翻译的内容:
以下是一个在ComboBox中呈现枚举的示例,其中第一项用于提示用户进行选择。
枚举
public enum BookCategories
{
    [Description("选项")]
    Select = 0,
    [Description("太空旅行")]
    SpaceTravel = 1,
    [Description("冒险")]
    Adventure = 2,
    [Description("流行体育")]
    Sports = 3,
    [Description("汽车")]
    Automobile = 4,
    [Description("使用C#编程")]
    Programming = 5
}
用于在ComboBox中呈现的模型
public class BookContainer
{
    public Enum Name { get; set; }
    public string Description { get; set; }
    // 用于在ComboBox中显示
    public override string ToString() => Description;
}
获取枚举描述的代码
public static class EnumHelper
{
    /// <summary>
    /// 创建一个KeyValuePair,其中Key是描述,Value是枚举值
    /// </summary>
    /// <typeparam name="T">要处理的枚举</typeparam>
    public static List<KeyValuePair<string, Enum>> GetItemsAsDictionary<T>() =>
        Enum.GetValues(typeof(T)).Cast<T>()
            .Cast<Enum>()
            .Select(value => new KeyValuePair<string, Enum>(
                (Attribute.GetCustomAttribute(value.GetType()
                        .GetField(value.ToString())!,
                    typeof(DescriptionAttribute)) as DescriptionAttribute)!
                .Description, value))
            .ToList();
    public static List<BookContainer> Container<T>()
    {
        List<KeyValuePair<string, Enum>> data = GetItemsAsDictionary<T>();
        return data.Select(category 
            => new BookContainer() { Name = category.Value, Description = category.Key })
            .ToList();
    }
}
表单代码,一个ComboBox,两个按钮
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Shown += OnShown;
    }
    private void OnShown(object? sender, EventArgs e)
    {
        categoriesComboBox.DataSource = EnumHelper.Container<BookCategories>();
    }
    private void CurrentButton_Click(object sender, EventArgs e)
    {
        BookContainer container = (categoriesComboBox.SelectedItem as BookContainer)!;
        if (Equals(container.Name, BookCategories.Select))
        {
            MessageBox.Show("请选择一个项目");
        }
        else
        {
            MessageBox.Show($"选择是 {container.Name}");
        }
    }
    private void SetCurrentButton_Click(object sender, EventArgs e)
    {
        // 这里是如何设置需要的选定索引
        categoriesComboBox.SelectedIndex = 
            categoriesComboBox.FindString(BookCategories.Adventure.ToString());
    }
}

英文:
The following presents an Enum in a ComboBox where the first item is to prompt the user for a selection.
Enum
public enum BookCategories
{
    [Description("Options")]
    Select = 0,
    [Description("Space Travel")]
    SpaceTravel = 1,
    [Description("Adventure")]
    Adventure = 2,
    [Description("Popular sports")]
    Sports = 3,
    [Description("Cars")]
    Automobile = 4,
    [Description("Programming with C#")]
    Programming = 5
}
Model for presenting in a ComboBox
public class BookContainer
{
    public Enum Name { get; set; }
    public string Description { get; set; }
    // for displaying in ComboBox
    public override string ToString() => Description;
}
Code to get descriptions for the Enum
public static class EnumHelper
{
    /// <summary>
    /// Create a <see cref="KeyValuePair"/> where Key is the description,
    /// Value the enum value
    /// </summary>
    /// <typeparam name="T">enum to work with</typeparam>
    public static List<KeyValuePair<string, Enum>> GetItemsAsDictionary<T>() =>
        Enum.GetValues(typeof(T)).Cast<T>()
            .Cast<Enum>()
            .Select(value => new KeyValuePair<string, Enum>(
                (Attribute.GetCustomAttribute(value.GetType()
                        .GetField(value.ToString())!,
                    typeof(DescriptionAttribute)) as DescriptionAttribute)
                !.Description, value))
            .ToList();
    public static List<BookContainer> Container<T>()
    {
        List<KeyValuePair<string, Enum>> data = GetItemsAsDictionary<T>();
        return data.Select(category 
            => new BookContainer() { Name = category.Value, Description = category.Key })
            .ToList();
    }
}
Form code, a ComboBox, two buttons
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Shown += OnShown;
    }
    private void OnShown(object? sender, EventArgs e)
    {
        categoriesComboBox.DataSource = EnumHelper.Container<BookCategories>();
    }
    private void CurrentButton_Click(object sender, EventArgs e)
    {
        BookContainer container = (categoriesComboBox.SelectedItem as BookContainer)!;
        if (Equals(container.Name, BookCategories.Select))
        {
            MessageBox.Show("Please make a selection");
        }
        else
        {
            MessageBox.Show($"Selection is {container.Name}");
        }
    }
    private void SetCurrentButton_Click(object sender, EventArgs e)
    {
        // here is how to set the selected index if needed
        categoriesComboBox.SelectedIndex = 
            categoriesComboBox.FindString(BookCategories.Adventure.ToString());
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论