简单的Windows窗体数据绑定

Dan*_*nny 1 c# data-binding winforms

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

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

问题2:当GUI之外的其他内容更改String属性时,如何在另一个方向(成员数据 - > GUI)上触发更新?我不想实现INotifyPropertyChanged接口并将NotifyPropertyChanged添加到setter.我认为通过使用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!"
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

this.bindingSource1.DataSource = this;
Run Code Online (Sandbox Code Playgroud)

我想你忘了分配数据源.