【问题标题】:C# use Summary tag of an enum [duplicate]C#使用枚举的摘要标签[重复]
【发布时间】:2020-04-05 23:30:30
【问题描述】:

我有以下枚举:

public enum eFlexCreateMode
{
    Man = 0,
    Auto = 1
}

我将其转换为字典以便在我的 wpf 页面中使用(绑定为组合框)

Dictionary<int, string> EnumCreateMode = Enum.GetValues(typeof(eFlexCreateMode)).Cast<eFlexCreateMode>().ToDictionary(t => (int)t, t => t.ToString());

<ComboBox Grid.Column="10" Width="70" ItemsSource="{Binding Path=EnumCreateMode, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:ViewerFlexConfig}}" SelectionChanged="Combo_SelectionChanged" DisplayMemberPath="Value" SelectedValuePath="Value" SelectedValue="{Binding ConfigObject.Create_Mode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

现在我将我的枚举中每个项目的摘要标记放在我的组合框的工具提示中。有可能完成这样的任务吗?没有可用的文档

【问题讨论】:

  • 不,使用DescriptionAttribute。你可以通过反射得到它的内容。
  • (我假设您正在写关于 &lt;summary/&gt; 文档评论)是的,生成 xml 文档,加载它,找到枚举,找到枚举元素,阅读摘要......是的,很多工作...正如 Trea 所写:使用 DescriptionAttribute
  • 如果您希望您的 UI 与 任何枚举 一起使用,那么属性就是您的选择。否则在视图模型中手动创建Dictionary&lt;eFlexCreateMode, string&gt;(初始化getter-only属性),将组合框ItemsSource绑定到它,完成。

标签: c# wpf enums


【解决方案1】:

以下是获取描述值的简短示例。您应该添加适当的空检查等...这只是一个示例。

// Usage Example
static void Main()
{
    var chanelDesc = Channel.Wholesale.GetEnumDescriptionValue();
    Console.WriteLine(chanelDesc);
    Console.ReadKey();
}

public static class EnumExtensions
{
    public static string GetEnumDescriptionValue<T>(this T @enum) where T : struct
    {
        if(!typeof(T).IsEnum)
            throw new InvalidOperationException();

        return typeof(T).GetField(@enum.ToString()).GetCustomAttribute<DescriptionAttribute>(false).Description;
    }
}

public enum Channel
{
    [Description("Banked - Retail")]
    Dtc,
    Correspondent,
    [Description("Banked - Wholesale")]
    Wholesale
}

【讨论】:

  • 好吧,它不适合绑定...... Sintar 提供了解决方案的链接,其中DescriptionAttribute 与自定义转换器一起使用
  • @Selvin,您使用 MVVM 作为设计模式,对吗?这是一个实用程序,它将获取属性值以设置您应该绑定到的属性...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 2016-11-24
  • 2019-05-01
  • 1970-01-01
相关资源
最近更新 更多