问题
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
回答3:
Defining Set as a simple baseComboBox.Items = value; is impossible because baseComboBox.Items is defined as ReadOnly. The problem is also the lack of a defined editor for such a collection.
Therefore, you should add the editor definition and instead of trying to replace the collection as one object - use AddRange:
[Editor("System.Windows.Forms.Design.StringCollectionEditor, " +
"System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
typeof(UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ComboBox.ObjectCollection Items
{
get
{
return baseComboBox.Items;
}
set
{
baseComboBox.Items.Clear();
baseComboBox.Items.AddRange(value.Cast<object>().ToArray());
}
}
来源:https://stackoverflow.com/questions/27004541/usercontrol-contains-a-combobox-but-the-items-set-at-design-time-are-not-in-the