سؤال

I have created a property to a custom windows form I made.

private List<object> values;

public List<object> Values
{
    get
    {
       return values;
    }
    set
    {
       values = value;
    }
}

It shows up in the property window on designer just fine. I go to the property value field and the button with '...' three dots shows. I click on the button and the window with which allows me to add items to list appears. I add them and click ok. No erro appears, but the items have not been saved.

My question is how to properly set this up so I can set the List<object> items in the property windows while in design?

هل كانت مفيدة؟

المحلول

In your Form1.Designer.cs, manually instantiate the List like this

this.Values = new List<object>();

After you've added items, the Form1.Designer.cs file will be recreated as per normal but the line above will be replaced by

this.Values = ((System.Collections.Generic.List<object>)(resources.GetObject("$this.Values")));

Alternatively, instantiate the list when you declare it.

private List<object> values = new List<object>();

public List<object> Values
{
    get
    {
        return values;
    }
    set
    {
        values = value;
    }
 }

نصائح أخرى

Thx to keyboardP. I changed mine code to what you suggested like

private List<object> values = new List<object>();

public List<object> Values { get { return values; } set { values = value; } }

It work exactly like I wanted.

One thing to note in case if anyone needs it. If you are using a custom class like List<CustomClass> instead of List<object>. In the "CustomClass" definition do this

[System.Serializable] public class CustomClass { ...... }

Otherwise, you will be getting an error when trying to add items to the List through the property window.

A different method would also be changing the List<CustomClass> to CustomClass[]

private CustomClass[] values;

public CustomClass[] Values { get { return values; } set { values = value } }

This second method I did not need to add the [System.Serializable] in the beginning of the CustomClass definition.

I hope this helped someone.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top