如何创建打开表单的自定义 PropertyGrid 编辑器项目?

问题描述 投票:0回答:2

我有一个 List<> (我的自定义类)。我想在 PropertyGrid 控件上的框中显示此列表中的特定项目。在框的末尾,我想要 [...] 按钮。单击时,它将打开一个表单,除其他外,该表单允许他们从列表中选择一个项目。关闭时,PropertyGrid 将更新以反映所选值。

任何帮助表示赞赏。

c# winforms propertygrid
2个回答
97
投票

您需要实现一个模态

UITypeEditor
,使用
IWindowsFormsEditorService
服务来显示它:

using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System;

class MyType
{
    private Foo foo = new Foo();
    public Foo Foo { get { return foo; } }
}

[Editor(typeof(FooEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(ExpandableObjectConverter))]
class Foo
{
    private string bar;
    public string Bar
    {
        get { return bar; }
        set { bar = value; }
    }
}
class FooEditor : UITypeEditor
{
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }
    public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value)
    {
        IWindowsFormsEditorService svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
        Foo foo = value as Foo;
        if (svc != null && foo != null)
        {            
            using (FooForm form = new FooForm())
            {
                form.Value = foo.Bar;
                if (svc.ShowDialog(form) == DialogResult.OK)
                {
                    foo.Bar = form.Value; // update object
                }
            }
        }
        return value; // can also replace the wrapper object here
    }
}
class FooForm : Form
{
    private TextBox textbox;
    private Button okButton;
    public FooForm() {
        textbox = new TextBox();
        Controls.Add(textbox);
        okButton = new Button();
        okButton.Text = "OK";
        okButton.Dock = DockStyle.Bottom;
        okButton.DialogResult = DialogResult.OK;
        Controls.Add(okButton);
    }
    public string Value
    {
        get { return textbox.Text; }
        set { textbox.Text = value; }
    }
}
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Form form = new Form();
        PropertyGrid grid = new PropertyGrid();
        grid.Dock = DockStyle.Fill;
        form.Controls.Add(grid);
        grid.SelectedObject = new MyType();
        Application.Run(form);
    }
}

注意:如果您需要访问有关属性上下文(父对象等)的信息,则

ITypeDescriptorContext
(在
EditValue
中)可以提供;它告诉您所涉及的
PropertyDescriptor
Instance
MyType
)。


0
投票

如果您正在寻找某种方法来控制 Foo 对象的 PropertyGrid 窗口中显示的内容,您可以将此方法添加到您的 Foo 类中:

public override string ToString()
{
    return string.Format(CultureInfo.CurrentCulture, "{0}",bar);
}

现在您可以让它显示您想要的 foo 类的任何属性(或多个属性)!

© www.soinside.com 2019 - 2024. All rights reserved.