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;
           
        }
最后,调用的结果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值