に親ViewModelに通知します。は、私は、<strong>C#の</strong>に<strong>MVVMパターン</strong>を<strong>のWindows 8.1ストアアプリの</strong>を書いていますMVVM
私は3つのviewmodels持っている: 1. BaseViewModel 2. StudentViewModel 3. StudentDashboardViewModel
そのような:
- を私はBaseViewModelを追加しました。
- 私はBaseViewModelのStudentViewModelを継承しました。
- 次に、StudentViewModelのStudentDashboardViewModelを継承しました。
私はページStudentDashboardPageを作って、私はStudentDashboardViewModelにそれをバインドさ。
私は別のクラスを経由して、プロパティの例を変更するStudentViewModelでIsBlackInをしようとしていますが、問題は、それはその子のviewmodel 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());
}
}
ここ コードでありますコードの後ろに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の基本に戻る。あなたのViewModelはなぜシングルトンですか? ViewModelは、対応するViewが表示され、アプリケーションの全期間にわたって表示されない限り生きているはずです。 – niksofteng
シングルトンから元に戻す予定ですが、通知問題はどうですか? –
View-Modelはビューを保持し、複数のビューで共有することもできますが、シングルトンではないことに同意します。 –