【WPF】【C#】【代码记录】构造ComboBox下拉的数据源(字典类型 Dictionary<string, T> T : Enum)

复制代码
#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
 }
复制代码

 

后续再定义类似字典只需三步:

 

posted @   春天花会开,  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示