WPF应用Binding之ItemsSource


一、ListBox显示简单的列表信息(未使用DataTemplate)

(1) Student类

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Id { get; set; }
    }

 (2) xaml

    
        
            
            
            
            
        
    

(3) C#代码逻辑

    private void ShowStudent()
    {
        List studentList = new List()
        {
            new Student(){Id = 2003, Name = "tim", Age = 20},
            new Student(){Id = 2004, Name = "tom", Age = 21},
            new Student(){Id = 2005, Name = "toni", Age = 21},
            new Student(){Id = 2006, Name = "fidy", Age = 23},
            new Student(){Id = 2007, Name = "andy", Age = 22},
        };

        //ListBox数据绑定
        listbox_Students.ItemsSource = studentList;//数据源
        listbox_Students.DisplayMemberPath = "Name";//ListBox只显示Student的Name属性

        //绑定被选中的id(2种方式均可)
#if true//方式1
        Binding binding = new Binding("SelectedItem.Id") { Source = listbox_Students };
#else//方式2
        Binding binding = new Binding();
        binding.Path = new PropertyPath("SelectedItem.Id");
        binding.Source = listbox_Students;
#endif
        txtbox_SelectId.SetBinding(TextBox.TextProperty, binding);
    }

二、ListBox显示Student信息(使用DataTemplate)

(1) Student类

    同上

(2) xaml

    
        
        
        
        
            
                
                    
                        
                        
                        
                    
                
            
        
    

(3) C#代码逻辑

        private void ShowStudent()
        {
            List studentList = new List()
            {
                new Student(){Id = 2003, Name = "tim", Age = 20},
                new Student(){Id = 2004, Name = "tom", Age = 21},
                new Student(){Id = 2005, Name = "toni", Age = 21},
                new Student(){Id = 2006, Name = "fidy", Age = 23},
                new Student(){Id = 2007, Name = "andy", Age = 22},
            };

            listbox_Students.ItemsSource = studentList;//数据源

            //绑定被选中的id(2种方式均可)
    #if true//方式1
            Binding binding = new Binding("SelectedItem.Id") { Source = listbox_Students };
    #else//方式2
            Binding binding = new Binding();
            binding.Path = new PropertyPath("SelectedItem.Id");
            binding.Source = listbox_Students;
    #endif
            txtbox_SelectId.SetBinding(TextBox.TextProperty, binding);



你可能感兴趣的:(Windows,APP)