在WPF中,Binding是可以实现数据关联在一起的桥梁,有了Binding,后台可以专心处理程序与算法,前台可以专注于UI设计。
通过绑定两个控件,可以实现数据的实时同步,且不需要写后台代码。本例Slider源控件,TextBox为目标控件,通过Text="{Binding ElementName=one, Path=Value,Mode=TwoWay,FallbackValue=0,UpdateSourceTrigger=PropertyChanged}" 实现数据的双向绑定。
控件之间数据绑定的固定格式为{Binding ElementName=源, Path=属性,Mode=方式,FallbackValue=默认值,UpdateSourceTrigger=触发方式}。
控件与资源之间,通过{Binding Source={StaticResource 资源名}}的方式进行绑定,如果资源还有其他属性,则需要指定Path对应的属性名,若纯文本内容,则不需要指定Path。
咏 鹅
鹅鹅鹅,曲项向天歌。
白毛浮绿水,红掌拨清波。
DataContext是指数据上下文,在WPF中,每一个控件都可以设置DataContext。通过上下文,可以自动匹配属性进行绑定。
后台代码:
///
/// DataContext.xaml 的交互逻辑
///
public partial class DataContext : Window
{
public DataContext()
{
InitializeComponent();
Student student = new Student()
{
Name = "Mag",
Age = 20,
Sex = "女",
Class = "一班"
};
this.GridData.DataContext = student;
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public string Class { get; set; }
}
前台代码:
姓名:
年龄:
性别:
班级:
普通的对象只能实现一次的单向绑定,如果要实现双向绑定,需要实现通知接口【System.ComponentModel.INotifyPropertyChanged】并在属性变更时进行通知。
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set { name = value;
OnPropertyChanged("Name");
}
}
private int age;
public int Age
{
get { return age; }
set { age = value;
OnPropertyChanged("Age");
}
}
private string sex;
public string Sex
{
get { return sex; }
set { sex = value;
OnPropertyChanged("Sex");
}
}
private string classes;
public string Classes
{
get { return classes; }
set { classes = value;
OnPropertyChanged("Classes");
}
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
在初始化时对DataCotext进行赋值,然后在变更事件中,更改属性值,则页面绑定的值也会随着改变。
姓名:
年龄:
性别:
班级:
///
/// NotifyPropertySample.xaml 的交互逻辑
///
public partial class NotifyPropertySample : Window
{
Person person;
public NotifyPropertySample()
{
InitializeComponent();
person = new Person()
{
Name = "Foo",
Age = 30,
Sex = "女",
Classes = "三班"
};
this.GridData.DataContext = person;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.person.Name = "Jack";
this.person.Age = 20;
this.person.Sex = "男";
this.person.Classes = "二班";
}
}
初始显示值:
点击刷新后显示: