Sivlerlight中的数据绑定
关注Silverlight很久了,从1.0看到3.0,也看了不少书,但是在学校里没有接触Sl项目的机会,所以很多知识很容易忘却,其实网上有很多银光的教程,李会军的系列教程我每个都在3.0环境下实现了一遍,说实话还是很喜欢这门技术的,
时间长了容易忘记,所以把自己看到的记下来,希望能跟银光爱好者们一起交流
使用标记进行数据绑定
为了方便起见,选择对象作为绑定源 ,新建一个Person类
public class Person { public Person() { } public string FirstName { get; set;} public string LastName { get; set; } }
XAML代码如下:
<TextBlock Name="textBlock3" Text="{Binding FirstName}" /> <TextBlock Name="textBlock4" Text="{Binding LastName}" />
简化起见,删除了样式部分,注意其中Text属性了使用{Binding PropertyName}语法
后天代码中:
public MainPage() { InitializeComponent(); Person p=new Person(){FirstName="David",LastName="Green"}; this.textBlock3.DataContext=p; this.textBlock4.DataContext = p; }
这样简单的标记数据绑定即完成了。
在此基础上我们扩展一下,显示分页显示多个Person信息
XAML需要简单的修改一下:
<Grid x:Name="PersonalPanel" Background="White"> <TextBlock Name="textBlock3" Text="{Binding FirstName}" /> <TextBlock Name="textBlock4" Text="{Binding LastName}" /> <Canvas Canvas.Left="120"> <Polygon Fill="Black" Points="0,5,10,0,10,10" MouseLeftButtonDown="prev"></Polygon> <Polygon Fill="Black" Points="15,0,15,10,25,5" MouseLeftButtonDown="next"></Polygon> </Canvas> </Grid>
后台代码:
private int pos = -1; private Person[] persons; public MainPage() { InitializeComponent(); persons = new Person[] { new Person { FirstName="David";,LastName="Grenn";}, new Person{FirstName="Dim";,LastName="Borin"}, new Person{FirstName="Tom";,LastName="White"}}; } public void prev(object sender, MouseButtonEventArgs e) { if (pos > 0) pos--; bind(); } public void next(object sender, MouseButtonEventArgs e) { if (pos < persons.Length - 1) pos++; bind(); } private void bind() { PersonalPanel.DataContext = persons[pos]; }
通过代码进行数据绑定
以上的绑定是在XAML进行声明的,我们也可以改为在后台进行绑定
XAML代码修改为:
<TextBlock Name="textBlock3" />
<TextBlock Name="textBlock4" />
后台代码改为:
public MainPage() { InitializeComponent(); persons = new Person[] { new Person{FirstName="David",LastName="Grenn"}, }; Binding b1 = new Binding(); b1.Mode = BindingMode.OneTime; firstName.SetBinding(TextBlock.TextProperty, b1); firstName.DataContext = persons[0].FirstName; Binding b2 = new Binding(); b2.Mode = BindingMode.OneTime; lastName.SetBinding(TextBlock.TextProperty, b2); lastName.DataContext = persons[0].LastName; }
其实很明显分为四个步骤:
创建绑定:Binding b1 = new Binding();
设置绑定模式:b1.Mode = BindingMode.OneTime;
将绑定附加到目标:firstName.SetBinding(TextBlock.TextProperty, b1);
设置数据上下文:firstName.DataContext = persons[0].FirstName;