Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force the PropertyGrid to show a custom dialog for a specific property?

I have a class with a string property, having both a getter and a setter, that is often so long that the PropertyGrid truncates the string value. How can I force the PropertyGrid to show an ellipsis and then launch a dialog that contains a multiline textbox for easy editing of the property? I know I probably have to set some kind of attribute on the property, but what attribute and how? Does my dialog have to implement some special designer interface?

Update: This is probably the answer to my question, but I could not find it by searching. My question is more general, and its answer can be used to build any type of custom editor.

like image 652
flipdoubt Avatar asked Dec 11 '08 15:12

flipdoubt


1 Answers

You need to set an [Editor(...)] for the property, giving it a UITypeEditor that does the edit; like so (with your own editor...)

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


static class Program
{
    static void Main()
    {
        Application.Run(new Form { Controls = { new PropertyGrid { SelectedObject = new Foo() } } });
    }
}



class Foo
{
    [Editor(typeof(StringEditor), typeof(UITypeEditor))]
    public string Bar { get; set; }
}

class StringEditor : UITypeEditor
{
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        IWindowsFormsEditorService svc = (IWindowsFormsEditorService)
            provider.GetService(typeof(IWindowsFormsEditorService));
        if (svc != null)
        {
            svc.ShowDialog(new Form());
            // update etc
        }
        return value;
    }
}

You might be ablt to track down an existing Editor by looking at existing properties that behave like you want.

like image 65
Marc Gravell Avatar answered Sep 23 '22 11:09

Marc Gravell