使用DataBinding更新标签

时间:2016-11-09 16:13:21

标签: c# winforms label

我的余额标签最初绑定到一个数字后,再次更改数据源不会再次更新该值。

我希望在更改数据库对象后自动更新Windows窗体标签,然后将其重新拉入constructorData.BankAccount

public class ConstructorData
{
    public Client Client { get; set; }
    public BankAccount BankAccount { get; set; }
}

private void frmTransaction_Load(object sender, EventArgs e)
{
    // Pretend we populated constructor data already

    // This line of code is working
    bankAccountBindingSource.DataSource = constructorData.BankAccount;
}

private void lnkProcess_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    constructorData.BankAccount = db.BankAccounts.Where(x => x.BankAccountId == constructorData.BankAccount.BankAccountId).SingleOrDefault();

    // What do I do here

    // Doesn't work
    bankAccountBindingSource.EndEdit();
    bankAccountBindingSource.ResetBindings(false);
}

自动生成的代码:

// 
// lblAccountBalance
// 
this.lblAccountBalance.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lblAccountBalance.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bankAccountBindingSource, "Balance", true));
this.lblAccountBalance.Location = new System.Drawing.Point(482, 71);
this.lblAccountBalance.Name = "lblAccountBalance";
this.lblAccountBalance.Size = new System.Drawing.Size(196, 23);
this.lblAccountBalance.TabIndex = 7;
this.lblAccountBalance.Text = "label1";

2 个答案:

答案 0 :(得分:2)

从这里开始(在表单加载中):

bankAccountBindingSource.DataSource = constructorData.BankAccount;

您直接绑定到BankAccount 实例,即使在INotifyPropertyChanged课程中实施ConstructorData(如评论中所示)也无济于事。

使用该设计,只要您将新BankAccount实例分配给ConstructorData.BankAccount属性(如显示的代码中),您还需要将其设置为DataSource BindingSource 1}}使用:

constructorData.BankAccount = db.BankAccounts.Where(x => x.BankAccountId == constructorData.BankAccount.BankAccountId).SingleOrDefault();
// What do I do here
bankAccountBindingSource.DataSource = constructorData.BankAccount;

答案 1 :(得分:2)

没有实施INotifyPropertyChanged伊万的答案正是你所需要的。

原因是因为您以这种方式将对象放在绑定源的DataSource中:BindingSource.DataSource = constructorData.BankAccount,因此它使用BankAccount属性中的对象作为数据源。如果更改constructorData.BankAccount的值,则不会更改BindingSource的数据源,它将包含上一个对象。例如,看一下这段代码:

var a = new MyClass("1");  // ← constructorData.BankAccount = something;
var b = a;                 // ← bindingSource.DataSource = constructorData.BankAccount.
a = new MyClass("2");      // ← constructorData.BankAccount = something else;

现在应该包含b的内容?你期望b包含MyClass("1")吗?当然没有。

有关更多信息,请查看此帖:

我可以使用INotifyPropertyChanged解决问题吗?

如果您在INotifyPropertyChanged中实施ConstructorData并以这种方式更改绑定,则是:

bankAccountBindingSource.DataSource = constructorData;
//...
this.lblAccountBalance.DataBindings.Add(new System.Windows.Forms.Binding("Text",
    this.bankAccountBindingSource, "BankAccount.Balance", true));