wpf 綁定ObservableCollection 的Count屬性

相信你們都遇到過這樣的需求,DataGrid裏顯示符合篩選條件的學生列表,上方TextBolck裏顯示學生總數,你們能夠這樣作:this

1,XAML代碼spa

 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代碼code

 

 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,運行效果orm

相關文章
相關標籤/搜索