首页 > 解决方案 > 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.
}

标签: c#wpfmvvm

解决方案


推荐阅读