WPF 使用LINQ 检索结果作为Binding源

通过LINQ我们可以方便的操作集合对象、DataTable对象而不必动辄就把好几层foreach循环嵌套在一起只是为了完成一个很简单的任务。

集合类

class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
界面代码,设定一个数据表格安装数据

<StackPanel Background="LightBlue"> <ListView x:Name="listViewStudents" Height="143" Margin="5"> <ListView.View> <GridView> <GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding Id}"/> <GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Name}"/> <GridViewColumn Header="Age" Width="80" DisplayMemberBinding="{Binding Age}"/> </GridView> </ListView.View> </ListView> <Button Content=" Load" Height="25" Margin="5,0" Click="Button_Click"/> </StackPanel>
后台代码

private void Button_Click(object sender, RoutedEventArgs e) { List<Student> stuList = new List<Student>(); { stuList.Add(new Student() { Id = 1, Name = "Tim", Age = 29 }); stuList.Add(new Student() { Id = 1, Name = "Tom", Age = 28 }); stuList.Add(new Student() { Id = 2, Name = "Kyle", Age = 27 }); stuList.Add(new Student() { Id = 3, Name = "Tony", Age = 26 }); stuList.Add(new Student() { Id = 4, Name = "Vina", Age = 25 }); stuList.Add(new Student() { Id = 5, Name = "Mike", Age = 24 }); }; this.listViewStudents.ItemsSource = from stu in stuList where stu.Name.StartsWith("T") select stu; }最后,调用的结果如下
WPF 使用LINQ 检索结果作为Binding源