【问题标题】:Simple Windows Forms data binding简单的 Windows 窗体数据绑定
【发布时间】:2013-04-11 02:03:21
【问题描述】:

假设我的表单中有一个 String 属性(并且该表单没有实现 INotifyPropertyChanged)。我还创建了一个 BindingSource 并将其 DataSource 设置为表单。然后我将一个文本框绑定到表单上的 String 属性(间接地,使用 BindingSource)。

问题 1:当我在运行时更改文本框中的值时,为什么不在 String 属性的 setter 中打断点?我认为将控件绑定到 String 属性将允许在这个方向上的更新(GUI -> 成员数据)自动发生

问题 2:当 GUI 以外的东西更改 String 属性时,如何触发另一个方向(成员数据 -> GUI)的更新?我不想实现 INotifyPropertyChanged 接口并将 NotifyPropertyChanged 添加到设置器。我认为通过使用 BindingSource 的 ResetBindings 我至少可以手动触发它

public partial class Form1 : Form
{
    private String m_blah;
    public String Blah
    { 
        get
        {
            return m_blah;
        }
        set
        {
            m_blah = value;
        }
    }

    public Form1()
    {
        InitializeComponent();
        textBox1.DataBindings.Add(new Binding("Text", bindingSource1, "Blah",true,DataSourceUpdateMode.OnValidation));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Blah = "Clicked!";
        this.bindingSource1.ResetBindings(false); //expecting the GUI to update and say "Clicked!"
    }
}

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案1】:
    this.bindingSource1.DataSource = this;
    

    我想你忘记分配数据源了。

    【讨论】:

    • 完美!设计者使用了这个语句而不是你提供的那个:this.bindingSource1.DataSource = typeof(binding_test.Form1);
    • @user1130698 你的问题解决了吗,勾选这个作为答案让我们知道...
    • 仍然想知道问题 2,如何在不实现 INotifyPropertyChanged 的​​情况下在另一个方向(成员数据 -> GUI)设置自动更新。目前,ResetBindings() 确实允许我手动执行此操作
    • 现在有办法做到这一点(至少我知道),ResetBinding - 用于手动更新,INotifyPropertyChanged 用于自动更新。由于更可控的性质,我建议使用 ResetBindings,但这取决于您想要做什么以及如何使用您的实体。
    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多