其中 OneWay 表示仅仅从数据源绑定到目标(通常是 UI 对象),单向的;
TwoWay 表示既可以从数据源绑定到目标,目标的更改也可以反馈给数据源,使其发生更新。
而 OneTime 是 OneWay 的一种特例,仅加载一次数据。随后数据的变更不会通知绑定目标对象。这样,可以带来更好的性能。
绑定的语法可以用大括号表示,下面是几个例子:
<TextBlockText="{Binding Age}"/>
等同于:
<TextBlock Text="{Binding Path=Age}" />
或者显式写出绑定方向:
<TextBlock Text="{Binding Path=Age,Mode=OneWay}" />
按照数据绑定的语义,默认是 OneWay 的,也就是说如果后台的数据发生变化,前台建立了绑定关系的相关控件也应该发生更新。
比如我们可以将文章 (1) 中提到的数据源改为当前页面的一个私有成员,然后在某个 button 点击事件中更改其中的值。代码如下:
public partial class Page : UserControl { private List<Person> persons; public Page() { InitializeComponent(); persons = new List<Person>(); for(var i=0; i< 5; i++) { persons.Add(new Person {name = "Person " + i.ToString(),Age = 20 + i}); } List1.DataContext = persons; } private voID button_Click(object sender,RoutedEventArgs e) { persons[0].name = "Tom"; } }
<ListBox x:name="List1"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel OrIEntation="Horizontal"> <TextBlock Text="{Binding Age}" margin="20,0" /> <TextBlock Text="{Binding name}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
但是我们点击 button 发现 ListBox 里的数据并没有发生变化。这是因为在数据源更新时,并没有发出任何通知。
我们可以让数据源中的对象实现 INotifyPropertyChanged 接口,在绑定的源属性值发生变化时,发出相关的通知信息。
代码如下:
public class Person: INotifyPropertyChanged { private int age; public int Age { get { return age; } set { age = value; NotifyPropertyChange("Age"); } } private string name; public string name { get { return name; } set { name = value; NotifyPropertyChange("name"); } } public event PropertyChangedEventHandler PropertyChanged; private voID NotifyPropertyChange(string propertyname) { if(PropertyChanged != null) { PropertyChanged(this,new PropertyChangedEventArgs(propertyname)); } } }
这个代码的原理很简单,这里就不解释了。这样以后,点击按钮,前台的 ListBox 中第一条数据的人名就变成了 Tom:
http://www.cnblogs.com/RChen/archive/2008/07/03/1235039.html
总结以上是内存溢出为你收集整理的SilverLight学习笔记之三数据绑定方式(上)全部内容,希望文章能够帮你解决SilverLight学习笔记之三数据绑定方式(上)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)