user6767845
user6767845

Reputation:

PropertyGrid --> Select object from List<object>

Is there a way to use a List like a selection-combobox in a propertyGrid?

For example, is it possible to have a class like this:

public class Foo
{
    [DisplayName(nameof(SelectedBar)),
    Browsable(true)]
    public Bar SelectedBar { get; set; } = null;

    [Browsable(false)]
    public List<Bar> Bars { get; set; } = new List<Bar>() { new Bar("Bar0"), new Bar("Bar1"), new Bar("Bar2") };
}

public class Bar
{
    public string Name;

    public Bar(string name) { Name = name; }

    public override string ToString()
    {
        return Name;
    }
}

And in propertyGrid let me select one of the objects in the List of "Bar".

Upvotes: 3

Views: 1925

Answers (2)

The Lemon
The Lemon

Reputation: 1391

It's not a direct answer, but if you know what/how many objects you are using at compile time you could use an enum paired with a dictionary in the background.

public enum someEnum {name1, name2, name3}
Dictionary<someEnum, object> backEndDictionary = new Dictionary<someEnum, object>();
backEndDictionary[someEnum.name1] = object1;
...

And then just make sure you have a property using the enum on your property grid

Upvotes: 0

user6767845
user6767845

Reputation:

Ok i found the solution for it:

You need a derived converter class with a static object-list variable:

    public class ListStringConverter: StringConverter
    {
        public static List<object> Objects = new List<object>();

        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            return new StandardValuesCollection(Objects);
        }
    }

And add a TypeConverter-Attribute with your converter to your selectedObject variable:

public class Foo
{
    public Foo()
    {
        ObjectListStringConverter.Objects = new List<object>(){ new Bar("Bar0"), new Bar("Bar1"), new Bar("Bar2") };
    }

    [DisplayName(nameof(SelectedBar)),
     Browsable(true),
     TypeConverter(typeof(ObjectListStringConverter))]
    public Bar SelectedBar { get; set; } = null;
}

public class Bar
{
    public string Name;

    public Bar(string name) { Name = name; }

    public override string ToString()
    {
        return Name;
    }
}

And at some point you need to fill the static object-list variable of your converter-class with your objects you want to have in your list, like i did it in the Foo-Constructor above.

EDIT: The list will show the ToString() method return value of each object you added to the list.

Upvotes: 2

Related Questions