WPF ListBox等控件绑定集合

 

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" });  
view plain
          //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属性,所以也就无法显示数据。
posted @ 2011-12-23 14:57  李董  阅读(1912)  评论(0)    收藏  举报