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