数据绑定(五)使用集合对象作为列表控件的ItemsSource

ItemsSource属性可以接收一个IEnumerable接口派生类的实例作为自己的值,ItemsSource里存放的是一条一条的数据,列表式控件的条目容器会为这些数据传上外衣,只要为ItemsControl对象设置了ItemsSource属性值,ItemsControl对象就会自动迭代其中的数据元素,为每一个数据元素准备一个条目容器,并使用Binding在条目容器与数据元素之间建立起关联,例子:

界面代码:

 

[html] view plain copy
 
  1. <StackPanel Background="LightBlue">  
  2.     <TextBlock Text="Student ID:" FontWeight="Bold"></TextBlock>  
  3.     <TextBox x:Name="textBox1"></TextBox>  
  4.     <TextBlock Text="Student List:" FontWeight="Bold"></TextBlock>  
  5.     <ListBox x:Name="listBoxStudents" Height="110"></ListBox>  
  6. </StackPanel>  


后台代码:

 

 

[csharp] view plain copy
 
    1. public MainWindow()  
    2. {  
    3.     InitializeComponent();  
    4.   
    5.     List<Student> stuList = new List<Student>()  
    6.     {  
    7.         new Student(){Id=0, Name="daijun", Age=11},  
    8.         new Student(){Id=1, Name="Tim", Age=12},  
    9.         new Student(){Id=2, Name="Tom", Age=13},  
    10.         new Student(){Id=3, Name="Kyle", Age=14},  
    11.         new Student(){Id=4, Name="Tony", Age=15}  
    12.     };  
    13.   
    14.     listBoxStudents.ItemsSource = stuList;  
    15.     listBoxStudents.DisplayMemberPath = "Name";  
    16.     Binding binding = new Binding();  
    17.     binding.Source = listBoxStudents;  
    18.     binding.Path = new PropertyPath("SelectedItem.Id");  
    19.     textBox1.SetBinding(TextBox.TextProperty, binding);  
    20. }  

posted on 2017-07-26 09:12  alex5211314  阅读(101)  评论(0编辑  收藏  举报

导航