3

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

4

2 回答 2

12

在这里找到答案: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);
}

现在您需要做的下一件事是创建 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
}
于 2010-09-28T20:02:16.173 回答
1

由于我无法发表评论,我将在此处发布:

您可以通过在 WindowsFormsEditorService.ShowDialog 的 CollectionEditor 的 okButton 上添加 Click 事件来获取 DialogResult

public System.Windows.Forms.DialogResult ShowDialog(Form dialog)
{
    ((System.Windows.Forms.Button)dialog.Controls.Find("okButton", true)[0]).Click += WindowsFormsEditorService_Click;
    return dialog.ShowDialog();
}

...

private void WindowsFormsEditorService_Click(object sender, EventArgs e)
{
    dr = DialogResult.OK;
}
于 2017-10-05T19:30:14.967 回答