如何在属性网格中显示下拉控件?

15

我在我的项目中添加了属性网格控件。 我需要在属性网格的一个字段中显示下拉框。 是否有解决方案可以应用此功能。


在你的 GridView 中使用 Template FieldItemTemplate - Ullas
1
不是网格,那是 Windows 表单中的 PropertyGrid 控件。 - Manivijay
这个链接可能比被接受的答案更有帮助 -> https://www.codeproject.com/Articles/23242/Property-Grid-Dynamic-List-ComboBox-Validation-and 虽然我认为使用一个ListBox可能有点过度,但我认为一个好的内存列表就可以胜任。 - Luke T O'Brien
1个回答

21
你需要在你的PropertyGrid中声明属性编辑器,然后将其添加到选择列表中。此示例创建了一个类型转换器,然后覆盖了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))]

这为你提供了通过覆盖方法来引入自己的行为的机会。

以下是一个更简单的示例,它允许属性的 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; } }

由于该属性是枚举类型,这些枚举值将自动传递并成为下拉选项。


使用这个,我怎样才能在下拉菜单中显示动态元素?我怎样才能为不同的属性传递自定义列表给FormatStringConverter - mrid
你可能想把它作为一个新问题发布。这可能比你意识到的更复杂。如果你真的是指“动态”,最大的问题可能是在你想要更改时刷新它。这更像是一个“一次性获取”的列表,而不是一个应该随时更改的列表。 - DonBoitnott

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接