2016-11-09 106 views
1

將我的餘額標籤初始綁定到數字後,再次更改數據源不會再次更新該值。使用DataBinding更新標籤

我想在數據庫對象更改後自動更新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"; 
+1

不知道在哪裏的標籤是在你的代碼,但你ConstructorData類應實現的INotifyDataChanging接口。 – LarsTech

+0

@LarsTech我從Visual Studio的數據源樹中拖動標籤,以便它自動創建一個綁定源並將標籤綁定到它。標籤中的哪些代碼可以提供幫助? – Ben

+0

[點擊](http://stackoverflow.com/q/1315621/1997232)。 – Sinatr

回答

1

由於這裏(形式負載內):你直接綁定到BankAccount實例

bankAccountBindingSource.DataSource = constructorData.BankAccount; 

,即使在ConstructorData類實現INotifyPropertyChanged (如評論中所建議的)將無濟於事。

有了這種設計,任何時候你分配一個新的BankAccount實例的ConstructorData.BankAccount財產(如所示的代碼),你也需要將其設置爲BindingSourceDataSource使用:

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

沒有實現INotifyPropertyChanged伊萬的答案正是你所需要的。

的原因是因爲你把一個對象的綁定源這樣的數據源: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的來解決這個問題?

如果要實現ConstructorDataINotifyPropertyChanged和更改綁定這種方式,是:

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