2012-12-21 97 views
1

我使用DataBindings從我的客戶對象到組合框。我試圖實現的行爲是標籤文本將反映選擇的名稱。爲什麼我的標籤沒有通過組合框更新

using System; 
using System.Collections.Generic; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
    Customer selectedCustomer; 
    List<Customer> list = new List<Customer>(); 

    public Form1() 
    { 
     InitializeComponent(); 
     selectedCustomer = new Customer() { Id = 2, FirstName = "Jane" }; 
    } 

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     label1.Text = selectedCustomer.FirstName; 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

     list.Add(new Customer() { Id = 1, FirstName = "John" }); 
     list.Add(new Customer() { Id = 2, FirstName = "Jane" }); 

     comboBox1.DisplayMember = "FirstName"; 
     comboBox1.ValueMember = "Id"; 
     comboBox1.DataSource = list; 
     comboBox1.DataBindings.Add("Text", selectedCustomer, "FirstName"); 
    } 
    } 

    public class Customer 
    { 
     public int Id { get; set; } 
     public string FirstName { get; set; } 
    } 
} 

回答

2

你應該選擇的項目分配給selectedCustomer領域:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    selectedCustomer = (Customer)comboBox1.SelectedItem; 
    label1.Text = selectedCustomer.FirstName; 
} 

如果你想標籤文本自動改變,你應該添加標籤綁定(目前將其添加到組合框):

label1.DataBindings.Add("Text", selectedCustomer, "FirstName"); 

但是文字也不會更新。爲什麼?由於標籤被綁定到客戶的具體實例(一個在時間上的結合增加) - 標籤將反映客戶的變化勢必:

selectedCustomer.FirstName = "Serge"; 

但同樣 - 什麼都不會發生,如果你會改變客戶的名稱。爲什麼?由於客戶應該實現INotifyPropertyChanged接口,提高事件通知有關名稱標籤更改:

public class Customer : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    private string _firstName; 

    public int Id { get; set; } 

    public string FirstName 
    { 
     get { return _firstName; } 
     set 
     { 
      _firstName = value; // well, it's better to check if value changed 
      if (PropertyChanged !=null) 
       PropertyChanged(this, new PropertyChangedEventArgs("FirstName")); 
     } 
    }   
} 

現在,如果你會改變選擇客戶的名稱,新值將出現在標籤。這就是數據綁定在winforms中的工作方式。

+0

但不是DataBindings應該自動更新源(在這種情況下是selectedCustomer對象)? – Rod

+0

@Rod問題是當選擇改變時你沒有更新'selectedCustomer'字段 –

+0

你可以爲標籤添加綁定label1.DataBindings.Add(「Text」,selectedCustomer,「FirstName」); –

相關問題