代码之家  ›  专栏  ›  技术社区  ›  Roxy'Pro

如何在组合框C_wpf中显示枚举的StringValue(Title)

  •  0
  • Roxy'Pro  · 技术社区  · 7 年前

    我正在使用小的WPF应用程序,我需要将枚举加载到我的组合框中,作为用户在添加新产品时可能选择的可能性,如下所示:

    我的枚举:

    public enum ProductTypeEnum : int
    {
        Unknown = 0,
    
        [StringValue("Final product for sale")]
        FinalProduct = 1,
    
        [StringValue("Ingredient for product")]
        Material = 2
    
    }
    

    以下是当我获取值并将其显示在组合框中时,它在我的C WPF应用程序中的外观:

    var myEnums = ProductTypeEnum.GetValues(typeof(ProductTypeEnum));
    
    
    if(myEnums.Length > 0)
    {
        cmbArticleType.ItemsSource = myEnums;
      //cmbArticleType.DisplayMemberPath = "SOMETHING.. WHATEVER IT AINT WORKED";
    
    }
    

    enter image description here

    你可以看到我的真实价值观。” 最终产品 “而不是” 销售最终产品 他说:“这是一个很好的选择。”

    [StringValue("Final product for sale")]

    我想展示一下 销售最终产品 因为它在组合框中看起来更自然(有空格等)=)

    谢谢你们的帮助 干杯

    在mm8帮助后编辑:

    如何从中获取实际值,并将其转换为整数,因为枚举值包含0、1、2、3等:

    enter image description here

    enter image description here

    但ArticleType不提供值,所以我可以将其强制转换为整数并存储到数据库?

    1 回复  |  直到 7 年前
        1
  •  1
  •   mm8    7 年前

    给定以下提取属性值的方法:

    public static string GetStringValue(Enum value)
    {
        Type type = value.GetType();
        FieldInfo fieldInfo = type.GetField(value.ToString());
        StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
            typeof(StringValueAttribute), false) as StringValueAttribute[];
        return attribs.Length > 0 ? attribs[0].StringValue : null;
    }
    

    …您可以创建具有 Description 财产:

    cmbArticleType.ItemsSource = myEnums.OfType<ProductTypeEnum>().Select(x => new { Value = x, Description = GetStringValue(x) });
    cmbArticleType.DisplayMemberPath = "Description";
    cmbArticleType.SelectedValuePath = "Value";
    

    您可以从 SelectedValue 性质 ComboBox :

    ProductTypeEnum selectedValue = (ProductTypeEnum)cmbArticleType.SelectedValue;