MVVM从父视图模型到子视图模型共享数据的正确方法是什么?

时间:2019-05-07 10:44:27

标签: c# wpf mvvm

在我的WPF应用程序中,我应该从父视图模型共享ObservableCollection以乘以子视图模型,并且子视图模型还应该订阅CollectionChanged事件。如果我通过子模型的构造函数的参数传递集合,那么它们的数量将会增加,可能在将来。

我考虑了Mediator和EventAggregator模式,但是我不明白如何在我的情况下正确应用它们。

class ViewModel : INotifyPropertyChanged
{
     protected void OnPropertyChanged( ... ) { ... }
}

class MainViewModel : ViewModel
{
    public ObservableCollection<ChildVM_1> Childs_1 { get; }
    public ObservableCollection<ChildVM_2> Childs_2 { get; }
    public ObservableCollection<ChildVM_3> Childs_3 { get; }

    public void Load( ... )
    {
        // Fill Childs_1 and Childs_2
        foreach( ... )
        {
            object par1 = ...;
            object par2 = ...;
            Childs_3.Add( new ChildVM_3( par1, par2 ) );
        }
    }
}

class ChildVM_1 : ViewModel { ... }
class ChildVM_2 : ViewModel { ... }
class ChildVM_3 : ViewModel
{
    // Selected value for ComboBox
    public SubChildVM SelectedValue
    {
        get{ ... }
        set
        {
            ...
            OnPropertyChanged();
        }
    }
    // Items Source for ComboBox
    public ObservableCollection<SubChildVM> SubChilds { get; }

    public ChildVM_3( object par1, object par2 )
    {
        object par3 = ...;
        foreach( ... )
        {
            if( ... )
            {
                 SubChilds.Add( new SubChildVM_1( par1, par2, par3 /* Here I need MainViewModel.Childs_1 */ );
            }
            else
            {
                 SubChilds.Add( new SubChildVM_2( par1, par2, par3 /* Here I need MainViewModel.Childs_2 */ );
            }
        }
}

abstract class SubChildVM : ViewModel{ ... }
class SubChildVM_1 : SubChildVM 
{
     // Selected value for nested ComboBox;
     public ChildVM_1 SelectedValue 
     {
        get{ ... }
        set
        {
            ...
            OnPropertyChanged();
        }
     }

     // IsEnabled property for ComboBoxItem.
     // Determines whether this item can be selected from the drop-down list.
     public bool IsEnabled
     {
        get{ ... }
        set
        {
            ...
            OnPropertyChanged();
        }
     }
     // Items Source for nested ComboBox
     // What the best way to retrive this reference from MainViewModel???
     public ObservableCollection<ChildVM_1> Childs_1 { get; }

     public SubChildVM_1( object par1, object par2, object par3 )
     {
          IsEnabled = Childs_1.Count > 0;
          if( IsEnabled )
          {
              // Set default selected value
              SelectedValue = Childs_1.First();
          }
          Childs_1.CollectionChanged += UpdateIsEnabled;
     }

     private void UpdateIsEnabled( ... )
     {
         IsEnabled = Childs_1.Count > 0;
     }
}

class SubChildVM_2 : SubChildVM 
{
    // Same as SubChildVM_1 but with ChildVM_2 references.
}

0 个答案:

没有答案