win8第七步数据绑定

基础

参数:要绑定的字段、绑定模式(OneTime加载是绑定一次,OneWay单向绑定,TwoWay双向绑定)、双向绑定的控件

<TextBox Text="{Binding Value,Mode=TwoWay,ElementName=slider1}" HorizontalAlignment="Left" Margin="151,145,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="586"/>

private Person p1 = new Person() { Name="zhaoyion",Age=24};

txt1.DataContext = p1;

上面是一个完整绑定,如果一个一个绑定你觉得麻烦也可以直接吧数据绑定到txt1的容器控件上比如grid1.DataContext = p1;这样就不用一个一个的给txt设置了,子控件会自动继承父控件的DataContext。

实体继承INotifyPropertyChanged,然后再属性set中实现事件,这个事件的意思是当数据值发生改变时触发,如果不实现这个事件,当值发生改变时控件上的内容不变。

    public class Person : INotifyPropertyChanged
    {
        private string _name;
        private int _age;
public int Age { get { return _age; } set { _age = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Age")); } } } public string Name { get { return _name; } set { _name = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public override string ToString() { return Name+" "+Age; } public event PropertyChangedEventHandler PropertyChanged; }

 

 

 

posted @ 2014-03-20 17:30  东方小花猪  阅读(144)  评论(0编辑  收藏  举报