1、ListBox用来显示多项内容,设定集合数据到ItemSource属性上。

     ListBox的Item既可以是一个string,也可以是一个class,或者是一个Button等等。

     对于自定义对象集合,DisplayMemberPath设定对象的显示属性名,SelectedValuePath设定选定对象的标志值。

 

2、当ListBox的选择项发生变化时SelectionChanged事件触发;

     SelectedItem是ListBox被选中项指定的对象;

     SelectedValue是ListBox被选中项指定的对象的“SelectedValuePath”属性对象的属性的值。    

 

3、实例应用。

3.1、定义一个Student类

1     class Student
2     {
3         public string Name { get; set; }
4         public int Age { get; set; }
5     }
View Code

3.2、定义一个泛型,将ListBox的ItemSource属性指向这个泛型。

1             List<Student> student = new List<Student>();
2             Student stu1 = new Student();
3             stu1.Name = "张三";
4             stu1.Age = 18;
5             student.Add(stu1);
6 
7             student.Add(new Student { Name="李四", Age=19});
8 
9             lstStudent.ItemsSource = student;
View Code

3.3、设定ListBox的DisplayMemberPath和SelectedValuePath。

1         <ListBox Name="lstStudent" DisplayMemberPath="Name" SelectedValuePath="Age" Height="100" HorizontalAlignment="Left" Margin="173,12,0,0"  VerticalAlignment="Top" Width="120" SelectionChanged="lstStudent_SelectionChanged">
2         </ListBox>
View Code

3.4、SelectionChanged事件

1         private void lstStudent_SelectionChanged(object sender, SelectionChangedEventArgs e)
2         {
3             object selectitem = lstStudent.SelectedItem;
4             object selectvalue = lstStudent.SelectedValue;
5 
6             MessageBox.Show(selectvalue.ToString());
7         }
View Code

3.5、运行结果

 

posted on 2014-03-02 22:04  恩恩爸爸  阅读(1174)  评论(0编辑  收藏  举报