为什么我的标签没有通过组合框更新

时间:2012-12-21 00:22:30

标签: c# winforms data-binding

我正在使用客户对象的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; }
  }
}

1 个答案:

答案 0 :(得分: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中的工作原理。