wpf 绑定ObservableCollection 的Count属性

相信大家都遇到过这样的需求,DataGrid里显示符合筛选条件的学生列表,上方TextBolck里显示学生总数,大家可以这样做:

1,XAML代码

 1 <Window x:Class="ObservableCollectionDemo.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:ObservableCollectionDemo="clr-namespace:ObservableCollectionDemo"
 5         Title="MainWindow"
 6         Height="350"
 7         Width="525">
 8     <Window.DataContext>
 9         <ObservableCollectionDemo:MainWindowViewModel />
10     </Window.DataContext>
11     <Grid>
12         <Grid.RowDefinitions>
13             <RowDefinition Height="Auto" />
14             <RowDefinition />
15         </Grid.RowDefinitions>
16         <TextBlock>学生总数:<Run Text="{Binding Students.Count, Mode=OneWay}" /></TextBlock>
17         <DataGrid Grid.Row="1"
18                   ItemsSource="{Binding Students}" />
19     </Grid>
20 </Window>

2,.CS代码

 

 1 public partial class MainWindow : Window
 2     {
 3         public MainWindow()
 4         {
 5             InitializeComponent();
 6         }
 7     }
 8 
 9     public class Student
10     {
11         public string Name { get; set; }
12         public int Age { get; set; }
13     }
14 
15     public class MainWindowViewModel
16     {
17         public ObservableCollection<Student> Students { get; set; }
18 
19         public MainWindowViewModel()
20         {
21             this.Students = new ObservableCollection<Student>();
22             for (int i = 0; i < 5; i++)
23             {
24                 this.Students.Add(new Student()
25                 {
26                     Name = string.Format("学生{0}", i),
27                     Age = 10 + i
28                 });
29             }
30         }
31     }

3,运行效果

posted on 2015-08-17 20:04  明月几时有25  阅读(1677)  评论(0编辑  收藏  举报