c# - 使用 DataBinding 更新标签

标签 c# winforms label

在我的余额标签最初绑定(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 实例,甚至实现INotifyPropertyChangedConstructorData类(如评论中所建议的)将无济于事。

使用该设计,您可以随时分配一个新的 BankAccount实例到 ConstructorData.BankAccount属性(如代码所示),您还需要将其设置为 DataSourceBindingSource使用:

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/

相关文章:

c# - 为什么我不能使 BackgroundWorker() 按预期工作?

c# - 如何使用 native MongoDB.Driver 将 mongo 脚本转换为纯 C# 代码?

Swift 更新标签(带有 HTML 内容)需要 1 分钟

数据库中的 Java 项目不会添加到我创建的列表中

c# - 来自 dbml 的 UpdateOnSubmit?

c# - 抽象类中的内部抽象方法的目的是什么?

c# - 如何检测 mp3 文件何时播放完毕

c# - 如何在 Windows.Forms 中制作 float (工具提示)控件?

c# - 流布局面板问题

javascript - D3 - 饼图和力导向标签