我在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
我打算从单身人士恢复,但通知问题呢? –
视图模型可以超越他们的观点,甚至可以被多个视图共享,但我同意他们不应该是单身人士。 –