【发布时间】:2016-05-04 06:30:42
【问题描述】:
我正在用 C#、MVVM 模式编写一个 Windows 8.1 Store App。
我有 3 个 ViewModel: 1.基础视图模型 2.学生视图模型 3.StudentDashboardViewModel
就像:
- 我添加了 BaseViewModel。
- 我从 BaseViewModel 继承了 StudentViewModel。
- 然后,我从 StudentViewModel 继承了 StudentDashboardViewModel。
我创建了一个页面 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;
}
}
【问题讨论】:
-
回到 MVVM 基础。为什么你的 ViewModels 是单例的? ViewModel 应该只在显示相应的 View 时才有效,而不是在整个应用程序生命周期内。
-
我打算从单例恢复,但是通知问题呢?
-
视图模型可以比它们的视图寿命更长,甚至可以被多个视图共享,但我同意它们不应该是单例的。
-
如果在派生类绑定到 UI 后更改基类中的属性值,则其值不会反映在 UI 中。所以你在派生类中进行,即在 StudentDashboardViewModel 类中。我同意这不是将 ViewModels 用作单例的好习惯。
标签: c# wpf mvvm windows-phone-8.1 windows-8.1