windows中的双向数据绑定形式为c#

时间:2015-04-17 11:30:03

标签: c# winforms datagridview 2-way-object-databinding

我正在阅读一篇关于winform中双向数据绑定的文章,我测试了他们的代码,它运行正常。我不知道winform中的双向数据绑定。这是文章网址: http://tech.pro/tutorial/776/csharp-tutorial-binding-a-datagridview-to-a-collection

请查看我的代码并告诉我我是否朝着正确的方向前进?还有其他更好的选择来实现相同或复杂的情况。只是寻找指导。

这是我的完整代码

namespace PatternSearch
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void btnBindData_Click(object sender, EventArgs e)
        {
            BindingList<Car> cars = new BindingList<Car>();

            cars.Add(new Car("Ford", "Mustang", 1967));
            cars.Add(new Car("Shelby AC", "Cobra", 1965));
            cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));

            dataGridView1.DataSource = cars;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.DataSource != null)
            {
                BindingList<Car> cars = dataGridView1.DataSource as BindingList<Car>;
                cars.Where(d => d.Make == "Ford").First().Make = "My Ford000";
            }
            else
                MessageBox.Show("Grid has no data");
        }
    }


    public class Car : INotifyPropertyChanged
    {
        private string _make;
        private string _model;
        private int _year;

        public event PropertyChangedEventHandler PropertyChanged;

        public Car(string make, string model, int year)
        {
            _make = make;
            _model = model;
            _year = year;
        }

        public string Make
        {
            get { return _make; }
            set
            {
                _make = value;
                this.NotifyPropertyChanged("Make");
            }
        }

        public string Model
        {
            get { return _model; }
            set
            {
                _model = value;
                this.NotifyPropertyChanged("Model");
            }
        }

        public int Year
        {
            get { return _year; }
            set
            {
                _year = value;
                this.NotifyPropertyChanged("Year");
            }
        }

        private void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

感谢

0 个答案:

没有答案