WPF绑定ListBox
- class Student
- {
- public string sno { get; set; }
- public string sname { get; set; }
- public string sage { get; set; }
- }
定义实体类Student
- <ListBox Height="163" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="217" >
- <ListBox.ItemTemplate>
- <DataTemplate>
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="{Binding sno}"/>
- <TextBlock Text="{Binding sname}"/>
- <TextBlock Text="{Binding sage}"/>
- </StackPanel>
- </DataTemplate>
- </ListBox.ItemTemplate>
- </ListBox>
XAML页面设置绑定格式和字段
- List<Student> students = new List<Student>();
- students.Add(new Student { sno = "1", sname = "王井", sage = "20" });
- students.Add(new Student { sno = "2", sname = "高瑞", sage = "21" });
- students.Add(new Student { sno = "3", sname = "刘欢", sage = "21" });
- listBox1.Items.Clear();
- listBox1.ItemsSource = students;
后台绑定数据