可以通过提供网格PropertyGrid
;这使用了System.ComponentModel
非常灵活但非常复杂的实现。但是,要提供建议值 - 您GetStandardValues
使用TypeConverter
. 完整示例:
(编辑:需要CanConvertFrom
/ConvertFrom
作为组合工作)
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public class MyType
{
[TypeConverter(typeof(GiveMeOptionsConverter))]
public string SomeProperty {get;set;}
private class GiveMeOptionsConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string) return value;
return base.ConvertFrom(context, culture, value);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // true is drop-down; false is combo
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
// this gives you the `MyType` instance if you need it
var obj = (MyType)context.Instance;
return new StandardValuesCollection(
new[] { "abc", "def", "ghi" });
}
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var grid = new PropertyGrid {
Dock = DockStyle.Fill,
SelectedObject = new MyType()
})
using (var form = new Form { Controls = { grid } })
{
Application.Run(form);
}
}
}
}