1

这是我的自定义控件类:

// Extended ComboBox where ill change some property.
public class ExtComboBox : ComboBox
{
    ...
}

// ExtButton is a control that i am going to drop on Form from ToolBox.
public partial class ExtButton : Button
{
    public ExtComboBox ComboBoxInsideButton { get; set; }

    public ExtButton()
    {
        InitializeComponent();


        ComboBoxInsideButton = new ExtComboBox();
        ComboBoxInsideButton.Text = "hi!";

        Controls.Add(ComboBoxInsideButton);
    }
}

基本上,当我将此控件添加到表单时,顶部按钮上会出现 ComboBox。不要问我为什么需要这个:D

现在,如果我需要更改 ComboBox 文本,我只需使用:

extButton1.ComboBoxInsideButton.Text = "aaa";

一切正常.. 但是 :) 当我尝试在设计模式下更改某些 ComboBox 属性(窗口属性 -> 展开 ComboBoxInsideButton -> 将文本更改为“bbb”)时,在重建或运行项目 ComboBox 属性将被重置(ExtButton.Designer 。CS)

问题1:如何用一些默认属性值初始化子控件,所以当Form上的控件出现错误时,所有设置都会被添加?

问题2:如何在设计时更改子控件的属性。

编辑:
在这里回答:设计器不会为子控件的属性生成代码。为什么?
添加[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]解决问题。

4

1 回答 1

1

我写了一篇关于如何创建自定义 UserControl 并在此处访问其成员的简短说明。几乎,您似乎想要向您添加属性以ExtComboBox公开ComboBox您想要更改的属性。然后,在 中ExtButton,您将能够.在运行时使用 来更改这些值。

另外,不要这样做:

public ExtComboBox ComboBoxInsideButton { get; set; }
...
ComboBoxInsideButton = new ExtComboBox();

public ExtComboBox comboBoxInsideButton = null;
...
comboBoxInsideButton = new ExtComboBox();

private请务必了解和之间的区别public。如果你把它放在另一个控件上,我不确定你是否想要你ExtComboBoxpublic

希望这可以帮助。

于 2012-08-29T16:46:04.970 回答