有没有办法在属性网格之外使用CollectionEditor?

Jas*_*son 2 c# collectioneditor

我正在替换我的属性网格,这将允许我更好地自定义我的UI.我在表单上放了一个按钮,希望点击后会弹出一个CollectionEditor并允许我修改我的代码.当我使用PropertyGrid时,我需要做的就是向指向我的CollectionEditor的属性添加一些属性并且它有效.但是如何手动调用CollectionEditor呢?谢谢!

Jas*_*son 11

在这里找到答案:http://www.devnewsgroups.net/windowsforms/t11948-collectioneditor.aspx

为了防止上面链接的网站有一天消失,这就是它的要点.但是,代码是从上面的链接逐字的; 评论是我的.

假设您有一个带有ListBox和按钮的表单.如果要使用CollectionEditor编辑ListBox中的项目,可以在EventHandler中执行以下操作:

private void button1_Click(object sender, System.EventArgs e)
{
    //listBox1 is the object containing the collection.  Remember, if the collection
    //belongs to the class you're editing, you can use this
    //Items is the name of the property that is the collection you wish to edit.
    PropertyDescriptor pd = TypeDescriptor.GetProperties(listBox1)["Items"];
    UITypeEditor editor = (UITypeEditor)pd.GetEditor(typeof(UITypeEditor));
    RuntimeServiceProvider serviceProvider = new RuntimeServiceProvider();
    editor.EditValue(serviceProvider, serviceProvider, listBox1.Items);
}
Run Code Online (Sandbox Code Playgroud)

现在,您需要做的下一件事是创建RuntimeServiceProvider().这是上面链接中的海报写的代码来实现这个:

public class RuntimeServiceProvider : IServiceProvider, ITypeDescriptorContext
{
    #region IServiceProvider Members

    object IServiceProvider.GetService(Type serviceType)
    {
        if (serviceType == typeof(IWindowsFormsEditorService))
        {
            return new WindowsFormsEditorService();
        }

        return null;
    }

    class WindowsFormsEditorService : IWindowsFormsEditorService
    {
        #region IWindowsFormsEditorService Members

        public void DropDownControl(Control control)
        {
        }

        public void CloseDropDown()
        {
        }

        public System.Windows.Forms.DialogResult ShowDialog(Form dialog)
        {
            return dialog.ShowDialog();
        }

        #endregion
    }

    #endregion

    #region ITypeDescriptorContext Members

    public void OnComponentChanged()
    {
    }

    public IContainer Container
    {
        get { return null; }
    }

    public bool OnComponentChanging()
    {
        return true; // true to keep changes, otherwise false
    }

    public object Instance
    {
        get { return null; }
    }

    public PropertyDescriptor PropertyDescriptor
    {
        get { return null; }
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)