WPF的ItemsControl设置数据源以及Binding使用
Student类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace BindingLINQ 8 { 9 public class Student 10 { 11 public int Id { get; set; } 12 public string Name { get; set; } 13 public int Age { get; set; } 14 } 15 }
1. 为ItemsControl类型的控件赋值,这里使用的是ListView,
只需要将集合直接赋值给 控件的 ItemsSource即可
namespace BindingLINQ { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<Student> list = new List<Student>() { new Student(){Id=1,Name="f1",Age=9}, new Student(){Id=2,Name="f2",Age=19}, new Student(){Id=3,Name="f3",Age=29} }; lstStudent.ItemsSource = list;//赋值 } } }
2.然后在XAML中只需要将ListView行的格式设置好,控件将会自动循环将数据输出
1 <Window x:Class="BindingLINQ.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="MainWindow" Height="350" Width="525"> 5 <Grid> 6 <ListView x:Name="lstStudent" Height="100" Width="200"> 7 <ListView.View> 8 <GridView> 9 <!--将标题和每一列的数据绑定好,这里一行的数据就对于ItemsSource中的一个对象的各个属性--> 10 <GridViewColumn Header="Id" Width="30" DisplayMemberBinding="{Binding Id}"/> 11 <GridViewColumn Header="Name" Width="30" DisplayMemberBinding="{Binding Name}"/> 12 <GridViewColumn Header="Age" Width="30" DisplayMemberBinding="{Binding Age}"/> 13 </GridView> 14 </ListView.View> 15 </ListView> 16 </Grid> 17 </Window>