在父ViewModel中访问ViewModel属性

时间:2017-05-22 05:09:43

标签: c# wpf mvvm navigation viewmodel

我正在使用此技术在视图之间导航:https://social.technet.microsoft.com/wiki/contents/articles/30898.simple-navigation-technique-in-wpf-using-mvvm.aspx

我有主ViewModel,菜单按钮绑定到SelectedViewModel属性更改命令:

class MainViewModel : INotifyPropertyChanged 
{
    public ICommand SomeViewCommand { get; set; }
    public ICommand OtherViewCommand { get; set; }
    private object selectedViewModel;
    public event PropertyChangedEventHandler PropertyChanged;

    public object SelectedViewModel
    {
        get { return selectedViewModel; }
        set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
    }

    public MainViewModel()
    {
        SomeViewCommand = new RelayCommand<object, object>(null, (object o) => OpenSomeView());
        OtherViewCommand = new RelayCommand<object, object>(null, (object o) => OpenOtherView());
    }

    private void OpenSomeView()
    {
       SelectedViewModel = new SomeViewModel();
    }

    private void OpenOtherView(object obj)
    {
       if(SelectedViewModel != null && SelectedViewModel.GetType() == typeof(SomeViewModel))
       {
          SomeViewModel s = (SomeViewModel)SelectedViewModel;

          // always 0
          if (s.NumberOfChanges > 0)
          {
             MessageBox.Show("test", "Error");
          }

          // SelectedViewModel = new OtherViewModel(); after confirmation dialog
       }
       else
          SelectedViewModel = new OtherViewModel();
    }

    private void OnPropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

}

如果我在SomeView中,我想在切换到OtherView之前检查其属性(更改次数),并向用户显示确认对话框以确认其操作。我需要当前值,但任何属性似乎都有其初始化值。为什么呢?

这样做最干净的方法是什么?我知道可以通过使属性静态来完成,但这对我来说似乎很脏。

1 个答案:

答案 0 :(得分:0)

在OnPropertyChanged方法中,您可以设置NumberOfChanges。