绑定数据,重要的就是三个方面:绑定到哪,什么数据,怎样绑定
首先,我们现在页面上拖曳一个ListView控件,调节一下它的大小和位置。下面是前台代码(这里用的是XAML,暂时不涉及HTML5+CSS3):
注意,这边要给ListView唯一指定一个x:Name="listBind",这样才能才能让后台有目标去把数据给谁。这个就解决了我们要绑定到哪里的问题。
<ListView x:Name="listBind" Height="289" Width="340">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock FontSize="40" Text="{Binding stuName}"/>
<Button Content="{Binding stuAge}" FontSize="40" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
其次就是在后台做文章了,我们定义一个类:
这边利用get,set应该不陌生,这个和在三层架构中的model层定义的是一样的。
public class Student
{
public string stuName { get; set; }
public int stuAge { get; set; }
}
然后就是new一个Student对象,往里面添加值了,这边又有两种方法:
一种是类似java的方法(不知道java是不是有更简便的方法,这种方法个人感觉有点麻烦):
Student stu = new Student { stuName = "钢铁侠", stuAge = 40 };
Student stu1 = new Student { stuName = "蜘蛛侠", stuAge = 40 };
Student stu2 = new Student { stuName = "蝙蝠侠", stuAge = 40 };
Student stu3 = new Student { stuName = "绿巨人", stuAge = 40 };
Student stu4 = new Student { stuName = "黑寡妇", stuAge = 40 };
Student stu5 = new Student { stuName = "美国队长", stuAge = 40 };
List<Student> stuList = new List<Student>();//泛型,这个也是java中的写法
stuList.Add(stu);
stuList.Add(stu1);
stuList.Add(stu2);
stuList.Add(stu3);
stuList.Add(stu4);
stuList.Add(stu5);
还有一个是C#的写法:
List<Student> stuList = new List<Student>
{
new Student{ stuName = "钢铁侠", stuAge = 40 },
new Student{ stuName = "蜘蛛侠", stuAge = 40 },
new Student{ stuName = "蝙蝠侠", stuAge = 40 },
new Student{ stuName = "黑寡妇", stuAge = 40 },
new Student{ stuName = "绿巨人", stuAge = 40 }
};
以上的不同写法都完成了一个目的,就是给stuList赋值了。这也解决了第二个问题,数据从哪里来的问题。
最后我们就是要完成绑定的步骤了。这个只需要一行代码就能把数据送到前台的ListView让其显示。这样就完成了最后一个问题,怎样绑定的问题。
注意:这里的listBind就是前台的ListView的唯一指定。
listBind.ItemsSource = stuList;
运行程序,就能看到ListView里面有值了,如下图所示: