ViewModelBase && ObservableObject

在Mvvm中,ViewModel和Model都需要具有通知界面更新数据的能力,这都要借助于WPF中的

INotifyPropertyChanged 接口,每一个ViewModel和Model都要去实现接口就太麻烦,于是作为

Mvvm框架的MvvmLight直接为我们提供了基类,并已经实现了这个接口。ViewModel继承自ViewModelBase

,Model继承自ObservableObject。在更新属性时,调用RaisePropertyChanged()来通知界面更新。

  public class Student : ObservableObject
{
private string name; public string Name
{
get
{
return name;
}
set
{
name = value;
RaisePropertyChanged(() => Name);
}
}
}

另外ViewModelBase还提供了一个判断当前是否设计时的属性IsInDesignMode,这个属性用于在ViewModel

中区分当前是运行时还是设计时,设计时可以显示一些模拟数据,运行时就显示真实数据,对UI开发人员是一个

比较友好的东西。

class AppViewModel : ViewModelBase
{
private ObservableCollection<Student> _students; public ObservableCollection<Student> Students
{
get
{
return _students;
}
set
{
_students = value;
RaisePropertyChanged(() => Students);
}
} public AppViewModel()
{
if (IsInDesignMode)
{
//模拟数据
Students = new ObservableCollection<Student>()
{
new Student(){Name = "MaYun"}
};
}
else
{
//运行时
Students = ISchool.GetAllStudents();
}
}
}

有了这2个基类的帮助,我们还需要在界面上进行正确的绑定

<Window x:Class="MvvmDemo.Views.AppView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AppView" Height="300" Width="300">
<Grid>
<ListView ItemsSource="{Binding Students}">
<ListView.View>
<GridView>
<GridViewColumn Header="姓名" DisplayMemberBinding="{Binding Name}"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>

ListView的ItemSource绑定到了ViewModel上的Students集合,此时Vs中还不能显示数据,那是因为,

我们并没有将View和ViewModel联系起来,View的DataContext就是ViewModel,下面我们将提到一个重要

的类ViewModelLocator(视图模型定位器)

最新文章

  1. Attribute富文本使用方法
  2. IDEA【 MyBatis Plugin】 插件免费完美运行
  3. [转]利于ThreadLocal管理Hibernate Session
  4. about云资源汇总V1,3
  5. 移动端版本兼容js
  6. css margin collapse
  7. 单片机串口通讯RXD与TXD如何对接详解
  8. 【 D3.js 入门系列 — 3 】 做一个简单的图表!
  9. android软键盘的管理和属性的设置
  10. KODExplorer可道云-轻松搭建属于自己/团队的私有云网盘服务
  11. springmvc注入类 NoUniqueBeanDefinitionException: No qualifying bean of type [] is defined: expected single错误
  12. 使用Android Studio手把手教你将应用打包+代码混淆
  13. 四、Linux的常用命令
  14. HTTPS 基本流程 转载 https://zhuanlan.zhihu.com/p/27395037
  15. nf_conntrack
  16. Hbase记录-Hbase Web管理工具
  17. php 路途一点启示
  18. BZOJ2707: [SDOI2012]走迷宫(期望 tarjan 高斯消元)
  19. Post-installation steps for Chromium | Fedora
  20. cube-ui

热门文章

  1. 组内Linq培训记录
  2. 0008《SQL必知必会》笔记04-子查询、联接与组合查询
  3. Drupal7网站+IIS7.0+PHP+MySql
  4. Linux换源+编译内核总结
  5. C语言 时间函数的学习和总结
  6. linux GD库安装
  7. R语言学习笔记(一)
  8. 【转】最长回文子串的O(n)的Manacher算法
  9. AC日记——简单密码 openjudge 1.7 10
  10. C与CPP 在线手册查找