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(視圖模型定位器)