传智播客——数据绑定基础

数据绑定基础

Slider:进度条

<Slider Name = "slider1"...></Slider>

<TextBox Text = "{Binding Value, ElementName = slider1}"></TextBox>

 

写一个数据绑定的类:

  class Person

  {

  }

后台:

  Person p1 = new  Person();

  txtName.DataContext = p1;

  txtAge.DataContext = p1;

前端:

  <TextBox Text = "{Binding Name}"

  <TextBox Text = "{Binding Age}"

 

尽量不要直接操控控件,而是新建一个类,new一个实例,给要绑定的控件设定DataContext

txtName.DataContext  = p1;

<TextBox Text = "{Binding Name}"

 

INotifyPropertyChanged

<TextBox TextChange

 

//.net内置的接口

//数据绑定会检测DataContext 是否实现了INotifyPropertyChanged

//如果实现了,就会监听PropertyChanged得知属性变化。

class Person:INotifyPropertyChanged

{

  private int age;

  public int Age

  {

    get

    {

      return age;

    }

    set

    {

      this.age = value;

      if(PropertyChanged != null)

      {

        PropertyChanged(this, new PropertyChangedEventArgs("Age"));

      }

    }

}

 

数据上下文:

Grid 的子控件都继承Grid的DataContex

子控件的数据也可以改修改默认的继承的DataContext

grid1.DataContext = p1;

txtName.DataContext = p2;

 

ListBox

lbPersons.ItemSource = list;

SelectedValue  SelectedValuePath = "Name"

SelectedItem

 

两个ListBox联动:

 

posted @ 2015-09-07 13:23  莫青铜  阅读(154)  评论(0编辑  收藏  举报