OneTime绑定:单次绑定,绑定后数据改变界面不会发生改变
OneWay绑定:单向绑定,这个是绑定的默认值,当我们改变数据源的值时,界面上面的值会发生改变,但当我们改名界面上面的值时,数据源数据不会发生变化(Eval)
TwoWay绑定:双向绑定,任意一方数据改变都会触发数据源或界面上面的值(BIND)
slider 进度滚动条
首先定义一个类Person
using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.Threading.Tasks;namespace GridExp{ public class Person : INotifyPropertyChanged { private string _name; private int _age; public int Id { get; set; } public string Name { get { return _name; } set { _name = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public int Age { get { return _age; } set { _age = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Age")); } } } public event PropertyChangedEventHandler PropertyChanged; }}
INotifyPropertyChanged接口规定了当属性更改时,向界面发送通知,这个事件时相对于Binding来说的,如果没有Binding,则不起任何作用
然后在前台定义3个控件
后台数据绑定
private Person p = new Person() { Name = "XXX", Age = 21 }; public GroupedItemsPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { bx.DataContext = p; } private void Button_Click_1(object sender, RoutedEventArgs e) { MessageDialog dlg = new MessageDialog(p.Name); dlg.ShowAsync(); } private void Button_Click_2(object sender, RoutedEventArgs e) { p.Name = DateTime.Now.Millisecond.ToString(); }
这里需要提一下,就是内层控件会继承外层控件的数据源(数据上下文),也就是说,上面数据绑定的代码如果写成
protected override void OnNavigatedTo(NavigationEventArgs e) { this.DataContext = p; }
也是可以的