我正在 C#, MVVM 模式中编写 Windows 8.1商店应用。
我有3个ViewModel: 1. BaseViewModel 2. StudentViewModel 3. StudentDashboardViewModel
就像:
我制作了一个Page StudentDashboardPage ,并将其绑定到 StudentDashboardViewModel 。
我正在尝试通过另一个类更改 StudentViewModel 中的属性示例 IsBlackIn ,但问题是它没有通知其子视图模型 StudentDashboardViewModel
那么,如何通知子视图模型父视图模型中的更改。 这是代码:
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());
}
}
代码后面的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;
}
}
答案 0 :(得分:2)
我可以通过3种方式看到StudentDashboardViewModel
可以了解IsBlackIn
中定义的StudentViewModel
属性可能发生的任何变化:
SetProperty<T>
(在BaseViewModel中)虚拟并覆盖StudentDashboardViewModel
并检查属性的名称。IsBlackIn
属性的setter设置为StudentViewModel
虚拟并覆盖StudentDashboardViewModel
。在前两种情况下,不要忘记调用基本方法,无论是SetProperty<T>
还是IsBlackIn
setter。
您拥有的第三个选项是组合视图模型(使用组合而不是继承)。也就是说,让StudentDashboardViewModel
接收StudentViewModel
的实例,然后收听通知IsBlackIn更改的事件。您可以收听INotifyPropertyChanged.PropertyChanged
或实施自己的自定义活动。