我在C#寫8.1的Windows Store應用,MVVM模式。通知父視圖模型在MVVM
我有3周的ViewModels: 1. BaseViewModel 2. StudentViewModel 3. StudentDashboardViewModel
它像:
- 我加入BaseViewModel。
- 我繼承了BaseViewModel的StudentViewModel。
- 然後,我從StudentViewModel繼承了StudentDashboardViewModel。
我做了一個頁面StudentDashboardPage,我又把它綁定到StudentDashboardViewModel。
我試圖更改屬性例如IsBlackIn在StudentViewModel通過另一個類,但問題是,它不通知其子視圖模型StudentDashboardViewModel。
那麼,如何通知child viewmodel父視圖模型的變化。 下面是代碼:
BaseViewModel:
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (Object.Equals(storage, value))
{
return false;
}
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
StudentViewModel:
public class StudentViewModel : BaseViewModel
{
private static StudentViewModel studentViewModel;
public static StudentViewModel Singleton()
{
if (studentViewModel == null)
{
studentViewModel = new StudentViewModel();
}
return studentViewModel;
}
private bool _IsBlackIn = false;
public bool IsBlackIn
{
get { return _IsBlackIn; }
set
{
SetProperty<bool>(ref _IsBlackIn, value);
}
}
}
StudentDashboardViewModel:
public class StudentDashboardViewModel : StudentViewModel
{
public static StudentDashboardViewModel studentDashboardViewModel;
public static StudentDashboardViewModel GetSingleInstance()
{
return studentDashboardViewModel ?? (studentDashboardViewModel = new StudentDashboardViewModel());
}
}
後面的代碼0
StudentDashboardPage頁:
public sealed partial class StudentDashboardPage : Page
{
private StudentDashboardViewModel studentDashvm;
public StudentDashboardPage()
{
this.InitializeComponent();
this.Loaded += StudentDashboardPage_Loaded;
}
private void StudentDashboardPage_Loaded(object sender, RoutedEventArgs e)
{
this.studentDashvm = StudentDashboardViewModel.GetSingleInstance();
this.DataContext = studentDashvm;
}
}
返回到MVVM基礎知識。爲什麼你的ViewModels單身居首位?只有在顯示相應的視圖時,ViewModel纔會處於活動狀態,而不是整個應用程序的使用壽命。 – niksofteng
我打算從單身人士恢復,但通知問題呢? –
視圖模型可以超越他們的觀點,甚至可以被多個視圖共享,但我同意他們不應該是單身人士。 –