简单数据绑定
1 无数据绑定
在实现这样的用户交互的时候:
在没有任何数据绑定机制实现的时候无非采用
this.nameTextBox.Text = person.Name;
this.ageTextBox.Text = person.Age.ToString();
这样的赋值的方法,而一旦数据改变了,将界面的值写回给person对象。
1.1对象改变
我们现在需要当对象发生改变的时候,UI的现实如何同步跟着改变呢?
实现起来还是比较复杂的,看如下代码就明白了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;//INotifyPropertyChanged
namespace SimpleDataBinding
{
class Person:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string PropName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(PropName));
}
}
public Person()
{
_Age = 0;
_name = "Null";
}
private string _name;
public string Name
{
get
{ return _name; }
set
{
if (value == _name)
{ return; }
_name = value;//注意:不能用this.Name来赋值,如果这样形成循环调用,栈溢出
Notify("Name");
}
}
private int _Age;
public int Age
{
get
{ return _Age; }
set
{
if (value == _Age) return;
_Age = value;
Notify("Age");
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace SimpleDataBinding
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class WithoutDataBinding : Window
{
private Person _person;
public WithoutDataBinding()
{
InitializeComponent();
//可以采用如下对象初始化,但本示例为了使用使用属性改变UI改变就先不赋值。
//_person = new Person
//{
// Name = "zhangying",
// Age = 28
//};
_person = new Person();
_person.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Name":
this.txt_name.Text = _person.Name;
break;
case "Age":
this.txt_age.Text = _person.Age.ToString();
break;
}
};
}
private void button2_Click(object sender, RoutedEventArgs e)
{
_person.Name = "zhangying";
_person.Age = 28;
}
}
}
1.2 UI改变
当UI的输入值发生变化的时候,如何同步对象的值呢?这需要给他们设置事件代码:
private void txt_name_TextChanged(object sender, TextChangedEventArgs e)
{
_person.Name = this.txt_name.Text;
}
private void txt_age_TextChanged(object sender, TextChangedEventArgs e)
{
int age = 0;
if(int.TryParse(this.txt_age.Text,out age)
{
_person.Age = age ;
}
}