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

转载于:https://www.cnblogs.com/moonlight-zjb/p/4737579.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值