12

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.

Community
  • 1
  • 1
flipdoubt
  • 13,897
  • 15
  • 64
  • 96
  • Thank you for this question, and the link to the other question about a multi-line property editor. I've been searching for how to do these things for a week. – spinjector May 31 '22 at 02:29

1 Answers1

21

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Thanks for the quick answer. I'm giving you a +1 for now and will mark this as the correct answer once I get a chance to try it out on my end. – flipdoubt Dec 11 '08 at 15:49
  • Is it possible to make 'Bar' textbox in propertygrid readonly so that the User cannot paste text directly into property textbox, but only through a modal dialog? Setter is not getting called if i add ReadOnly(true) attribute. – lerner1225 Apr 05 '16 at 10:43
  • @lerner1225 You need a do-nothing type converter - see http://stackoverflow.com/a/30194849/127670 – Ian Goldby Nov 08 '16 at 15:27