C#实现非枚举类型的在属性控件中可下拉选择(一)
1.效果图
2.对象类
public class People
{
[Category("自定义")]
[TypeConverter(typeof(OptionValuesTypeConvertor))]
[OptionCollection(1, 54, 6)]
public decimal ID { get; set; } = 1;
[Category("自定义")]
public string Name { get; set; }
[Category("自定义")]
[DisplayName("AA")]
public short? Age { get; set; }
[Category("自定义")]
public string Location { get; set; }
[Category("自定义")]
[TypeConverter(typeof(OptionValuesTypeConvertor))]
[OptionCollection("A", 54, null)]
public string Desc { get; set; } = "A";
}
3. 特性和类型转换器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace AttributeTest
{
public class OptionCollectionAttribute : Attribute
{
/// <summary>
/// 构造器
/// </summary>
public OptionCollectionAttribute(params object[] objArr)
{
if (objArr != null)
{
foreach (var obj in objArr)
{
OptionCollection.Add(obj);
}
}
}
/// <summary>
/// 获取可供选择的项目集合
/// </summary>
public List<object> OptionCollection { get; private set; } = new List<object>();
}
public partial class OptionValuesTypeConvertor : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true; //是否有下拉列表
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true; //是否不允许编辑
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
if (context.Instance != null)
{
//找到当前操作的属性
PropertyInfo currentProperty = context.Instance.GetType().GetProperties().FirstOrDefault(info => info.Name == context.PropertyDescriptor.Name);
if (currentProperty != null)
{
//找到当前操作的属性的OptionCollectionAttribute特性,并根据该特性的值得到可选集合
object[] optionCollectionAttributes = currentProperty.GetCustomAttributes(typeof(OptionCollectionAttribute), false);
if (optionCollectionAttributes != null)
{
object myAttribute = optionCollectionAttributes.FirstOrDefault(attribute => attribute is OptionCollectionAttribute);
if (myAttribute != null)
{
return new StandardValuesCollection((myAttribute as OptionCollectionAttribute).OptionCollection);
}
}
}
}
return base.GetStandardValues(context);
}
}
}