【问题标题】:WinForms. Design-time Data binding to child control's property赢表格。设计时数据绑定到子控件的属性
【发布时间】:2016-12-21 13:35:51
【问题描述】:

我正在开发自己的“MyTextBox”控件

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;
        }
    }
}

现在在设计时,我将“MyTextBox”放在表单上。在 Designer 的 PropertyGrid 中,我可以看到 myTextBox1 控件的“TextBox”属性在 Sub-Grid 中可见。

我还在表单中添加了一个“BindingSource”以进行数据绑定。

Sub-Grid 提供“Text”属性进行绑定,我将其绑定到 bindingSource1,就像我们通常绑定 texbox 的“Text”属性一样。我希望设计器生成以下代码:

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

上面的演练没有给出这种效果。我想知道是否有办法做到这一点。我的意图是在设计时对 MyTextBox 子级的 TextBox 的“文本”属性进行数据绑定。

【问题讨论】:

  • DataBinding 和 WinForms 有一条规则:不要使用它。如果你想使用数据绑定使用 WPF。
  • 老实说,我同意你的看法。自从我开始项目开发以来,我一直受到折磨:)。但无论如何我需要一个解决方案
  • 不要太早放弃。 Windows 窗体最有用的功能之一是数据绑定。
  • 另外,要向TextBox 添加按钮,您无需创建用户控件。您可以向TextBoxControls 集合添加一个按钮,例如将按钮的Dock 属性设置为停靠在右侧。

标签: c# winforms


【解决方案1】:

不要太早放弃。 Windows 窗体最有用的功能之一是数据绑定。根据您的要求,首先将您的 TextBox 属性更改为:

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

然后以这种方式在设计器中绑定用户控件的TextBoxText 属性:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2011-04-24
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多