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 lstStu = new List();
            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
            
                
                    
                        
                        
                        
                        
                        
                    
                
            


如上代码,如果设置lst.ItemsSource = lstStu,则可以显示对应的数据,如果lst.DataContext=lstStu,则无法显示数据,原因在于ItemsSource属性是IEnumerable类型,它会遍历传进去的集合,所以能读取集合中每个Student对象,而DataContext是object类型,传一个集合它就直接使用该集合,导致找不到Name,Age和Sex属性,所以也就无法显示数据。

你可能感兴趣的:(WPF)