我有自定义集合编辑器,我想以编程方式将项目添加到它的列表(集合)中,以便它们可以在列表框中显示。我怎么能这样做?我知道CollectionEditor的AddItems方法,但它将集合对象作为参数,但我无法找到获取CollectionEditor内部列表对象的方法......:/
[更新] 呃..正确的方法名称是'SetItems' [/更新]
[更新2] 我正在尝试做的源代码......
public class MyCollectionEditor : CollectionEditor
{
private Type m_itemType = null;
public MyCollectionEditor(Type type)
: base(type)
{
m_itemType = type;
}
protected override CollectionForm CreateCollectionForm()
{
Button buttonLoadItem = new Button();
buttonLoadItem.Text = "Load from DB";
buttonLoadItem.Click += new EventHandler(ButtonLoadItem_Click);
m_collectionForm = base.CreateCollectionForm();
TableLayoutPanel panel1 = m_collectionForm.Controls[0] as TableLayoutPanel;
TableLayoutPanel panel2 = panel1.Controls[1] as TableLayoutPanel;
panel2.Controls.Add(buttonLoadItem);
return m_collectionForm;
}
private void ButtonLoadItem_Click(object sender, EventArgs e)
{
if (m_itemType.Equals(typeof(MyCustomCollection)))
{
MyCustomItem item = ...load from DB...
//definition: SetItems(object editValue, object[] value);
SetItems( -> what goes here?! <- , new object[] { item });
}
}
}
[/ update 2]
答案 0 :(得分:0)
我可能会误解你的问题,但你不必先定义自己的收藏吗?然后使用EditorAttribute
进行装饰[EditorAttribute(typeof(System.ComponentModel.Design.CollectionEditor),typeof(System.Drawing.Design.UITypeEditor))]
答案 1 :(得分:0)
由于.NET Reflector和反射机制,我找到了解决方案。我没有使用SetItems方法,而是调用CollectionForm的私有方法:private void AddItems(IList instances)
,如下所示:
MethodInfo methodInfo = m_collectionForm.GetType().GetMethod("AddItems", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(m_collectionForm, new object[] { /* my items here */ });
PS。请参阅上面的其余代码...