黑马程序员_数据绑定,INotifyPropertyChanged接口,DataContext

来源:互联网 发布:那家博客公司数据准确 编辑:程序博客网 时间:2024/05/21 06:12

------- Windows Phone 7手机开发、.Net培训、期待与您交流! ------- 


1、两个控件之间的数据绑定
<Slider Name="slider1" Margin="0,40" Width="300" VerticalAlignment="Top" HorizontalAlignment="Center" ></Slider>
<TextBox Text="{Binding Value,ElementName=slider1}" Width="300" Height="30" HorizontalAlignment="Center"></TextBox>


2、数据绑定基础:
1)定义一个类:Person
2) new一个实例,让控件的DataContext引用对象:
Person p1 = new Person();
txtName.DataContext = p1
3)将控件的属性绑定到对象的属性,几乎所有的属性都可以这样绑定
 <TextBox Name="txtName" Text="{Binding Name}" Width="300" Height="30" HorizontalAlignment="Center"></TextBox>


3、INotifyPropertyChanged 接口
数据绑定会检测DataContext是否实现INotifyPropertyChanged 接口,如果实现,通过监听PropertyChanged通知属性改变。实现前台页面随后台对象属性的改变而改变。
例:public class Person:INotifyPropertyChanged
    {
        private int age;
        public int Age
        {
            get { return age; }
            set
            {
                this.age = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));
                }
            }
        }
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                this.name = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }




        public event PropertyChangedEventHandler PropertyChanged;
    }
4、所有子控件及其后代控件在没有指定DataContext的情况下都默认继承自其父控件的DataContext。
例: 
//前台
<Grid Name="grid1">
        <TextBox Name="txtAge" Text="{Binding Age}" ToolTip="{Binding Name}" Width="200" Height="30" Margin="59,164,258,125"></TextBox>
        <TextBox Name="txtName" Text="{Binding Name}" ToolTip="{Binding Age}" Width="200" Height="30" Margin="59,210,258,79"></TextBox>
</Grid>
//后台绑定       
   grid1.DataContext = p1;
   txtName.DataContext = p2;

原创粉丝点击