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; }
  }
}
4

1 回答 1

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 中的工作方式。

于 2012-12-21T00:27:44.710 回答