How to show Drop down control in Property Grid?

若如初见. 提交于 2019-12-10 12:38:18

问题


I am adding the Property grid control in my project. I have to show the Drop down box in one field of Property Grid. Is there any solution to apply this.


回答1:


You have to declare a type editor for the property in your PropertyGrid and then add to the list of choices. This example creates a Type Converter and then overrides the GetStandardValues() method to provide choices to the drop-down:

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);
    }
}

The key is the property being assigned a Type Converter in the line:

[TypeConverter(typeof(FormatStringConverter))]

That provides you with the opportunity to introduce your own behavior via overrides.

Here's a simpler example, which allows the Enum type of a Property to automatically provide its values to the PropertyGrid drop-down:

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; } }

By virtue of the fact that the property is an Enum type, those enum values pass through to become the drop-down options automatically.



来源:https://stackoverflow.com/questions/24503462/how-to-show-drop-down-control-in-property-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!