我在我的应用程序中有一个class
命名的产品,我想显示它以在Form
使用PropertyGrid
控件中进行编辑。class
产品有一个命名的field
MaterialId,它指定了构成产品的材料合金。我希望当产品class
显示在PropertyGrid
控件中时,field
MaterialId 会显示一个包含所有可用材料的下拉列表。物料清单由用户提供,因此必须在运行时定义。我尝试使用 aPropertyDescriptor
来修改dataSource
TextToComboConverter的字段class
。我已经注意到,检查 Visual Studio 中的 Locals,这dataSource
是在变量的Converter
属性下descriptor
,但我不知道如何访问dataSource
场地。我按照以下代码中的说明进行了尝试,但没有成功。有人可以告诉我正确的方法吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
using System.Reflection;
namespace PropertyGridDropDownList
{
public class Product
{
[Browsable(true)]
public string ProductName { get; set; }
[TypeConverter(typeof(TextToComboConVerter))]
[Browsable(true)]
public string MaterialId { get; set; }
[Browsable(true)]
public double Wheight { get; set; }
}
public class TextToComboConVerter : StringConverter
{
public List<string> dataSource;
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture,
object value)
{
return base.ConvertFrom(context, culture, value);
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(dataSource);
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Actually this list is supplied by user through a input form.
List<string> materialIdList = new List<string>();
materialIdList.Add("Material01");
materialIdList.Add("Material02");
materialIdList.Add("Material03");
materialIdList.Add("Material04");
materialIdList.Add("Material05");
//Create a instance of Product class.
Product product = new Product()
{
ProductName = "Product01",
MaterialId = "Material03",
Wheight = 100
};
//Define combobox for MaterialId.
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(product)["MaterialId"];
descriptor.Converter.dataSource = materialIdList; //This fails
//Show the Product class in a ProductGrid.
//I would like that itens of materialIdList was showed
//as a dropdown list in MaterialId field.
using (PropertyGrid propertyGrid = new PropertyGrid
{
Dock = DockStyle.Fill,
SelectedObject = product
})
using (Form form = new Form { Controls = { propertyGrid } })
{
Application.Run(form);
}
}
}
}