Data Binding doesn't work when I assign a new object instance to the bound variable

后端 未结 2 1369
旧巷少年郎
旧巷少年郎 2021-01-18 05:03

I have an object that I have bound to a control on a form using C# WinForms (targetting .NET 4.5.2). I have implemented INotifyPropertyChanged, and when I modif

2条回答
  •  醉梦人生
    2021-01-18 05:33

    To get the desired behavior, you should not bind directly to the concrete instance like you do currently:

    lblName.DataBindings.Add("Text", currentUser, "Name");
    

    Instead, you need some intermediary. The easiest is to use the BindingSource component for that purpose.

    Add a BindingSource field to the form:

    private BindingSource dataSource;
    

    Then initialize it and bind the controls to it one time (usually in form Load event):

    dataSource = new BindingSource { DataSource = typeof(User) };
    lblName.DataBindings.Add("Text", dataSource, "Name");
    // ...
    

    Now anytime you want to bind to a User instance, you simply assign it to the DataSource property of the BindingSource:

    initial:

    dataSource.DataSource = new User("Example Name");
    

    later:

    dataSource.DataSource = new User("New Name"); 
    

提交回复
热议问题