Winform 数据敏感(PropertyManager)
Winform开发已经有一段时间了,记得以前在Delphi里面,数据敏感的控件非常好用,但那个时候自己的开发水平还非常低,还不会面向对象编程。但那时候已经觉得数据敏感是非常好用的,转到了WINFORM开发以后,一直没去想这方面的事情,随着开发难度不断加深,面向对象编程,已经成为我的主要编程思路,但也因此出现了很多问题,例如一个对象的属性,显示在N个TextBox里面,然后我的操作就是反复的对TextBox赋值,反复的读取值,这个操作是最简单也是最直接的,但如果对象的属性很多,TextBox就会一样多,代码的编写就显得非常的重复。这个时候我就觉得数据敏感的重要性,为了工程及以后的开发,我还是放下工作,认真的研究一下Winform的数据绑定,在网上找了很多资料,终于确定我想要的东西PropertyManager就能给我。
下面就让我跟大家分享一下吧。
功能:一窗体上有多个TextBox,每一个TextBox绑定显示对象一个属性的值,通过更改TextBox的值,直接修改对象的属性;
实现:
对象People(Name,Age,Sex,Birthday)
1 public partial class Form_Member : Form
2 {
3 private People people;
4 private PropertyManager pm;
5
6 public Form_Member()
7 {
8 InitializeComponent();
9
10 people = new People();
11 people.Name="张三";
12 people.age="40";
13 people.Sex="男";
14 people.Birthday="1970-1-1";
15
16 TextBox_Name.DataBindings.Add("Text", people, "Name");
17 TextBox_Age.DataBindings.Add("Text", people, "Age");
18 TextBox_Sex.DataBindings.Add("Text", people, "Sex");
19 TextBox_Birthday.DataBindings.Add("Text", people, "Birthday");
20
21 pm = (PropertyManager)this.BindingContext[people];
22 }
23
24 //修改
25 private void Button_Edit_Click(object sender, EventArgs e)
26 {
27 people.Name = "李四";
28 people.Age="25";
29 people.Sex="男";
30 people.Birthday="1985-10-1";
31 pm.ResumeBinding();
32 }
33
34 //确认修改
35 private void Button_Sumbit_Click(object sender, EventArgs e)
36 {
37 pm.CancelCurrentEdit();
38 MessageBox.Show(people.Name);
39 MessageBox.Show(people.Age);
40 MessageBox.Show(people.Sex);
41 MessageBox.Show(people.Birthday);
42
43 }
44 }
2 {
3 private People people;
4 private PropertyManager pm;
5
6 public Form_Member()
7 {
8 InitializeComponent();
9
10 people = new People();
11 people.Name="张三";
12 people.age="40";
13 people.Sex="男";
14 people.Birthday="1970-1-1";
15
16 TextBox_Name.DataBindings.Add("Text", people, "Name");
17 TextBox_Age.DataBindings.Add("Text", people, "Age");
18 TextBox_Sex.DataBindings.Add("Text", people, "Sex");
19 TextBox_Birthday.DataBindings.Add("Text", people, "Birthday");
20
21 pm = (PropertyManager)this.BindingContext[people];
22 }
23
24 //修改
25 private void Button_Edit_Click(object sender, EventArgs e)
26 {
27 people.Name = "李四";
28 people.Age="25";
29 people.Sex="男";
30 people.Birthday="1985-10-1";
31 pm.ResumeBinding();
32 }
33
34 //确认修改
35 private void Button_Sumbit_Click(object sender, EventArgs e)
36 {
37 pm.CancelCurrentEdit();
38 MessageBox.Show(people.Name);
39 MessageBox.Show(people.Age);
40 MessageBox.Show(people.Sex);
41 MessageBox.Show(people.Birthday);
42
43 }
44 }
ResumeBinding()是刷新控件上的值;
CancelCurrentEdit()是确定更改,即将控件上的值更新到绑定的对象上;