如何在Property Grid中显示下拉控件?

Man*_*jay 9 propertygrid winforms

我在我的项目中添加了属性网格控件.我必须在Property Grid的一个字段中显示下拉框.有没有解决方案来应用它.

Don*_*ott 12

您必须在您的属性中声明一个类型编辑器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);
    }
}
Run Code Online (Sandbox Code Playgroud)

关键是在行中为属性分配了一个类型转换器:

[TypeConverter(typeof(FormatStringConverter))]
Run Code Online (Sandbox Code Playgroud)

这为您提供了通过覆盖介绍自己行为的机会.

这是一个更简单的示例,它允许属性的Enum类型自动为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; } }
Run Code Online (Sandbox Code Playgroud)

由于属性是枚举类型,这些枚举值会自动成为下拉选项.