1

我有自定义集合编辑器,我想以编程方式将项目添加到它的列表(集合)中,以便它们可以在列表框中可见。我怎么能这样做?我知道 CollectionEditor 的 AddItems 方法,但它将集合对象作为参数,但我无法找到获取 CollectionEditor 的内部列表对象的方法...:/

[更新] 呃.. 正确的方法名称是 'SetItems' [/update]

[更新 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 });
            }
        }
}

[/更新 2]

4

2 回答 2

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。请参阅上面的其余代码...

于 2009-07-28T11:31:28.287 回答
0

我可能误解了您的问题,但您不必先定义自己的收藏吗?然后用 EditorAttribute 装饰它

[EditorAttribute(typeof(System.ComponentModel.Design.CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]

于 2009-07-28T09:37:28.923 回答