在我的余额标签最初绑定(bind)到一个数字后,再次更改数据源不会再次更新该值。
我想在数据库对象更改后自动更新 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";
最佳答案
从这里开始(在表单加载内):
bankAccountBindingSource.DataSource = constructorData.BankAccount;
您直接绑定(bind)到 BankAccount
实例,甚至实现INotifyPropertyChanged
在ConstructorData
类(如评论中所建议的)将无济于事。
使用该设计,您可以随时分配一个新的 BankAccount
实例到 ConstructorData.BankAccount
属性(如代码所示),您还需要将其设置为 DataSource
的 BindingSource
使用:
constructorData.BankAccount = db.BankAccounts.Where(x => x.BankAccountId == constructorData.BankAccount.BankAccountId).SingleOrDefault();
// What do I do here
bankAccountBindingSource.DataSource = constructorData.BankAccount;
关于c# - 使用 DataBinding 更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40511419/