代码之家  ›  专栏  ›  技术社区  ›  Toto

C组合框上的数据绑定

  •  1
  • Toto  · 技术社区  · 15 年前

    我不能理解下面给出的代码的两个问题。我将一个组合框映射到一个自定义对象,每次组合框上选定的值更改时,自定义对象也会更改。

    public partial class MainForm : Form
    {
        private Person _person;
        public MainForm()
        {
            InitializeComponent();
            _person = new Person();
    
            //Populating the combox, we have this.comboBoxCities.DataSource = this.cityBindingSource;
            cityBindingSource.Add(new City("London"));
            cityBindingSource.Add(new City("Paris"));
            _person.BirthCity = new City("Roma");
            cityBindingSource.Add(_person.BirthCity);
            cityBindingSource.Add(new City("Madrid"));
    
            //Doing the binding
            comboBoxCities.DataBindings.Add("SelectedItem", _person, "BirthCity");
        }
    
        private void buttonDisplay_Click(object sender, EventArgs e)
        {
            MessageBox.Show("BirthCity=" + _person.BirthCity.Name);
        }
    
        private int i = 0;
        private void buttonAddCity_Click(object sender, EventArgs e)
        {
            City city = new City("City n°" + i++);
            cityBindingSource.Add(city);
            comboBoxCities.SelectedItem = city;
        }
    
    }
    
    public class Person
    {
        private City _birthCity;
        public City BirthCity
        {
            get { return _birthCity; }
            set
            {
                Console.WriteLine("Setting birthcity : " + value.Name);
                _birthCity = value;
            }
        }
    }
    
    public class City
    {
        public string Name { get; set; }
        public City(string name) { Name = name; }
        public override string ToString() { return Name; }
    }
    

    1-为什么我在一行中手动选择两次(或更多)组合框上的不同值时,我只收到一个对出生城市的调用。设置最后一个选择的值(只有当组合框失去焦点时,调用才会触发)?

    2-为什么当我单击按钮添加城市,然后单击按钮显示时,双面城市不是选中的城市(不是显示在Combox中的城市)

    1 回复  |  直到 15 年前
        1
  •  2
  •   XXXXX    15 年前
    为什么我在一行中手动选择两次(或更多)组合框上的不同值时,我只收到一个对出生城市的调用。用上一个选择的值设置(只有当组合框失去焦点时,调用才似乎启动)?

    这就是数据绑定的工作方式,在验证发生时数据从控件移动到属性,在控件失去焦点时进行验证。

    为什么当我单击按钮添加城市,然后单击按钮显示时,双层城市不是选中的城市(不是显示在Combox中的城市)

    我不知道。我创建了一个简单的表单(使用.NET 3.5 SP1的Visual C Express 2008),并逐字粘贴了您的代码,它按预期工作:在组合框中显示新城市。

    如果将comboxcities.focus();添加到buttonAddCity_Click()的末尾,您将确保新城市更早地被推到_Person.BirthCity,而不是在ValidateChildren()上。