WPF ListBox等控制元件繫結集合
阿新 • • 發佈:2019-01-29
public class Student { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } private string sex; public string Sex { get { return sex; } set { sex = value; } } } List<Student> lstStu = new List<Student>(); lstStu.Add(new Student() { Name = "Jay", Age = 20, Sex = "M" });
lstStu.Add(new Student() { Name = "Joey", Age = 21, Sex = "M" });
lstStu.Add(new Student() { Name = "Achilles", Age = 22, Sex = "M" });
lstStu.Add(new Student() { Name = "Jam", Age = 23, Sex = "M" });
lstStu.Add(new Student() { Name = "Jone", Age = 24, Sex = "M" });
lstStu.Add(new Student() { Name = "Jessi", Age = 25, Sex = "M" });
lstStu.Add(new Student() { Name = "Mand", Age = 26, Sex = "M" });
//Xaml中定義的ListBox <ListBox Name="lst"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <TextBlock Text="{Binding Path=Name}"></TextBlock> <TextBlock Text="{Binding Path=Age}"></TextBlock> <TextBlock Text="{Binding Path=Sex}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
如上程式碼,如果設定lst.ItemsSource = lstStu,則可以顯示對應的資料,如果lst.DataContext=lstStu,則無法顯示資料,原因在於ItemsSource屬性是IEnumerable型別,它會遍歷傳進去的集合,所以能讀取集合中每個Student物件,而DataContext是object型別,傳一個集合它就直接使用該集合,導致找不到Name,Age和Sex屬性,所以也就無法顯示資料。