How do I view object properties in PropertyGrid?
Asked Answered
T

1

12

At the moment I have an object of type A which is being viewed by the PropertyGrid. However, one of its properties is of type B. The property which is of type B is not expandable. How can I change this so that:

a) I can expand custom object property's b) Those changes are bound to that property

Here is the code I have so far:

using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace PropGridTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            A a = new A
            {
                Foo = "WOO HOO!",
                Bar = 10,
                BooFar = new B
                {
                    FooBar = "HOO WOO!",
                    BarFoo = 100
                }
            };

            propertyGrid1.SelectedObject = a;
        }
    }
    public class A
    {
        public string Foo { get; set; }
        public int Bar { get; set; }
        public B BooFar { get; set; }
    }
    public class B
    {
        public string FooBar { get; set; }
        public int BarFoo { get; set; }
    }
}
Tadich answered 23/4, 2011 at 20:23 Comment(0)
S
24

You can use the ExpandableObjectConverter class for this purpose.

This class adds support for properties on an object to the methods and properties provided by TypeConverter. To make a type of property expandable in the PropertyGrid, specify this TypeConverter for standard implementations of GetPropertiesSupported and GetProperties.

To use this converter, decorate the property in question with the TypeConverterAttribute, with typeof(ExpandableObjectConverter) as the constructor-argument.

public class A
{
    public string Foo { get; set; }
    public int Bar { get; set; }

    [TypeConverter(typeof(ExpandableObjectConverter))]
    public B BooFar { get; set; }
}
Sullins answered 23/4, 2011 at 20:28 Comment(2)
Thank you! It works exactly how I needed it to. I can't mark your answer as correct for 8 minutes or so though...but I will :DTadich
Oh Great, that was exactly what i needed and search for an hour.Crown

© 2022 - 2024 — McMap. All rights reserved.