-->

Usercontrol contains a combobox, but the Items set

2019-07-29 11:51发布

问题:

I have a user control that contains a textbox and a combobox. I have exposed the combobox's Item property to clients of the user control, thus:

public System.Windows.Forms.ComboBox.ObjectCollection Item
{
    get { return baseComboBox.Items; }
}

I added the user control to a windows form, and set the Items list using the property values editor in the form designer. I then ran the application, and the combobox's drop down list was empty. To confirm that the items added at design time were not in the list, I added the following two lines of code to the client form:

textBox1.Text = userControl1.Items.Count.ToString();
userControl1.Items.Add("Test item");

When I re-ran the application the test box showed a count of 0 (zero), and the drop-down list of the user control contained only "Test item".

Thinking that maybe the instance of the user control being referenced at design time is a different instance from that being referenced at run time, I set the user control's BackColor property at design time. When I re-ran the app, the user control's BackColor was what I had set it to in the designer.

Any ideas on why the design time setting of the Items does not carry over into the run time?

回答1:

You need an attribute:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ComboBox.ObjectCollection Item {
  get { return baseComboBox.Items; }
}


回答2:

Maybe you need the setter defined also, something like:

public System.Windows.Forms.ComboBox.ObjectCollection Item
{
    get { return baseComboBox.Items; }
    set { baseComboBox.Items = value; }
}

Or, maybe it's because you are exposing Item but setting Items