Wednesday, January 19, 2011

How do I change the type of control that is used in a .NET PropertyGrid

I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?

I would like to be able to use a RichTextBox to allow better formatting of the input value. Can this be done without creating a custom editor class?

  • I think what you are looking for is Custom Type Descriptors. You could read up a bit and get started here: http://www.codeproject.com/KB/miscctrl/bending_property.aspx

    I am not sure you can do any control you want, but that article got me started on propertygrids.

  • You can control whether the PropertyGrid displays a simple edit box, a drop-down arrow, or an ellipsis control.

    Look up EditorAttribute, and follow it on from there. I did have a sample somewhere; I'll try to dig it out.

  • To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box.

    What is nice is that you can reuse the existing implementations. So to add the ability to multiline edit a string you just do this...

    
            [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
            public override string Text
            {
                get { return _string; }
                set { _string = value; }
            }
    

    Another nice one they provide for you is the ability to edit an array of strings...

    
            [Editor("System.Windows.Forms.Design.StringArrayEditor, 
             System.Design, Version=2.0.0.0, 
             Culture=neutral, 
             PublicKeyToken=b03f5f7f11d50a3a", 
             typeof(UITypeEditor))]
            public string[] Lines
            {
                get { return _lines; }
                set { _lines = value; }
            }
    
    pmac : Thanks. That was perfect! One addition instead of typeof(UITypeEditor) you can use "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" found that after some compile erros

0 comments:

Post a Comment