简体   繁体   中英

WinForms. Design-time Data binding to child control's property

I am developing my own "MyTextBox" control

public class MyTextBox:UserControl
{
    TextBox textBox;
    Button button;

    public MyTextBox()
    {
         this.textBox = new TextBox();
         this.button = new Button();
         this.button.Click += button_Click;
         this.Controls.Add(this.textBox);
         this.Controls.Add(this.button);
    }

    public TextBox TextBox
    {
        get
        {
            return this.textBox;
        }
    }
}

Now at Design-time I am putting "MyTextBox" on a form. In the Designer's PropertyGrid I can see that "TextBox" property of myTextBox1 control is visible in a Sub-Grid .

I am also adding a "BindingSource" to the form for data binding.

The Sub-Grid is offering "Text" property for binding and I am binding it to the bindingSource1 just as we all usually bind texbox's "Text" property. I am expecting following code to be generated by the Designer:

    this.myTextBox1.TextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource1, "FullName"));

The walkthrough above is not giving this effect. I am wondering if there is a way of doing that. My intention is to data-bind "Text" property of the TextBox, childed by MyTextBox, at Design-time.

Don't give up too soon. One of the most useful features of Windows Forms is data-binding. For your requirement, first change your TextBox property to this:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TextBox TextBox
{
    get
    {
        return textBox1;
    }
}

then bind Text property of your TextBox of your user control in designer this way:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM