我在项目中添加了属性网格控件。 我必须在Property Grid的一个字段中显示下拉框。 是否有任何解决方案可以应用它。
答案 0 :(得分:11)
您必须在PropertyGrid
中为该属性声明一个类型编辑器,然后添加到选项列表中。此示例创建Type Converter,然后覆盖GetStandardValues()
方法以提供下拉菜单的选项:
private String _formatString = null;
[Category("Display")]
[DisplayName("Format String")]
[Description("Format string governing display of data values.")]
[DefaultValue("")]
[TypeConverter(typeof(FormatStringConverter))]
public String FormatString { get { return _formatString; } set { _formatString = value; } }
public class FormatStringConverter : StringConverter
{
public override Boolean GetStandardValuesSupported(ITypeDescriptorContext context) { return true; }
public override Boolean GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; }
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
List<String> list = new List<String>();
list.Add("");
list.Add("Currency");
list.Add("Scientific Notation");
list.Add("General Number");
list.Add("Number");
list.Add("Percent");
list.Add("Time");
list.Add("Date");
return new StandardValuesCollection(list);
}
}
密钥是在行中分配了类型转换器的属性:
[TypeConverter(typeof(FormatStringConverter))]
这为您提供了通过覆盖介绍自己行为的机会。
这是一个更简单的示例,它允许属性的枚举类型自动将其值提供给PropertyGrid
下拉列表:
public enum SummaryOptions
{
Sum = 1,
Avg,
Max,
Min,
Count,
Formula,
GMean,
StdDev
}
private SummaryOptions _sumType = SummaryOptions.Sum;
[Category("Summary Values Type")]
[DisplayName("Summary Type")]
[Description("The summary option to be used in calculating each value.")]
[DefaultValue(SummaryOptions.Sum)]
public SummaryOptions SumType { get { return _sumType; } set { _sumType = value; } }
由于属性是枚举类型,这些枚举值会自动成为下拉选项。