使用DataSourceUpdateMode.OnPropertyChanged进行数据绑定winform c#的优点是什么?

时间:2015-04-25 19:21:28

标签: c# winforms data-binding

首先看我的代码

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

这种方式我有约束力

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        BindingList<Car> ol;

        private void Form1_Load(object sender, EventArgs e)
        {
            Car carTest = new Car("Ford", "Mustang", 1967);
            ol = new BindingList<Car>();
            ol.Add(carTest);

            this.textBox1.DataBindings.Add("Text", ol, "Make", true, DataSourceUpdateMode.OnPropertyChanged);
            this.textBox2.DataBindings.Add("Text", ol, "Make", true, DataSourceUpdateMode.OnPropertyChanged);
            this.textBox3.DataBindings.Add("Text", ol, "Make");

            dataGridView1.DataSource = ol;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ol.Where(d => d.Make == "Ford").First().Make = "My Ford000";
        }

    }

i use `DataSourceUpdateMode.OnPropertyChanged` for one textbox and did not use for other textbox

this.textBox2.DataBindings.Add("Text", ol, "Make", true, DataSourceUpdateMode.OnPropertyChanged);
this.textBox3.DataBindings.Add("Text", ol, "Make");

在一个文本框中更改值时,更改也会反映在其他文本框中而不使用DataSourceUpdateMode.OnPropertyChanged,所以只是不了解DataSourceUpdateMode.OnPropertyChanged

的优势

即使通过以下方式更改数据源中的数据,所以更改也会反映在所有文本框中。

ol.Where(d => d.Make == "Ford").First().Make = "My Ford000";

please help me to understand right usage of `DataSourceUpdateMode.OnPropertyChanged` like when and where to use.

感谢

1 个答案:

答案 0 :(得分:3)

以下列方式添加绑定时:

textBox3.DataBindings.Add("Text", ol, "Make");

它使用DataSourceUpdateMode.OnValidation,您可以检查here。因此,如果您的控件具有一些验证规则,则验证失败时将不会更新基础值。另一方面,DataSourceUpdateMode.OnPropertyChanged将在任何情况下更新基础源。