#region 下拉 private Dictionary<string, T> getComboSource<T>(params T[] types) where T : Enum { var enumValues = types.Length > 0 ? types : (T[])Enum.GetValues(typeof(T)); return enumValues.ToDictionary(o => getTypeName(o), o => o); } private string getTypeName<T>(T type) where T : Enum { var member = type.GetType().GetMember(type.ToString()); if (member.Length > 0) { var attributes = member[0].GetCustomAttributes(typeof(DisplayAttribute), false); if (attributes.Length > 0) { return ((DisplayAttribute)attributes[0]).GetName(); } } return type.ToString(); } #endregion
调用的方式例如:
/// <summary> /// 形状下拉 /// </summary> public Dictionary<string, ShapeType> CalibrationShapeTypeComboSource { get { return _calibrationShapeTypeComboSource; } set { SetProperty(ref _calibrationShapeTypeComboSource, value); } } /// <summary> /// 有效、禁用区域下拉 /// </summary> public Dictionary<string, AreaType> AreaTypeComboSource { get { return _areaTypeComboSource; } set { SetProperty(ref _areaTypeComboSource, value); } } // 这样调用 CalibrationShapeTypeComboSource = getComboSource(ShapeType.Rectangle, ShapeType.Circle, ShapeType.RotatedRectangle, ShapeType.LineSegment); AreaTypeComboSource = getComboSource<AreaType>();
结果:
枚举要声明Display
public enum ShapeType { None, /// <summary> /// 线段 /// </summary> [Display(Name = "线段")] LineSegment, /// <summary> /// 矩形 /// </summary> [Display(Name = "矩形")] Rectangle, /// <summary> /// 旋转矩形 /// </summary> [Display(Name = "旋转矩形") RotatedRectangle, /// <summary> /// 圆形 /// </summary> [Display(Name = "圆形")] Circle, /// <summary> /// 多边形 /// </summary> [Display(Name = "多边形")] Polygon }
public enum AreaType { /// <summary> /// 有效区 /// </summary> [Display(Name = "有效区")] ValidArea, /// <summary> /// 屏蔽区 /// </summary> [Display(Name = "屏蔽区")] MaskedArea, /// <summary> /// 禁用区 /// </summary> [Display(Name = "禁用区")] DisabledArea }
标签:return,Name,ShapeType,C#,数据源,public,ComboBox,type,Display From: https://www.cnblogs.com/moon-stars/p/18474158