我有下面的枚举:
public enum eFlexCreateMode
{
Man = 0,
Auto = 1
}
我将其转换为字典以便在我的wpf页面中使用(绑定为combobox)
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}" />
现在,我将我的枚举的每个项目的摘要标记放入其中,我将使用它作为我的组合框的工具提示。有可能完成这样的任务吗?没有可用的文档
发布于 2019-12-12 14:46:51
下面是获取Description值的一个简短示例。您应该添加适当的null检查,等等。这只是一个例子。
// 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
}
https://stackoverflow.com/questions/59306867
复制