c# - 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.
}
解决方案
推荐阅读
- python - 实时处理程序将新数据从吉时利数字万用表附加到 csv 文件而不覆盖数据
- python - `re.Pattern.search()` 中的 UnicodeDecodeError
- c++ - 如果 operator!=() 使用 operator==() 的否定,我应该内联运算符 == 和 !=
- python - 用 Python 去噪一张照片
- css - 我不断收到“预期大括号”和“意外令牌”错误
- pandas - 什么是最好的方法,在熊猫数据框中应用函数或 for 循环来替换空值?
- r - R 根据访问日期为每个主题创建访问编号
- r - 使用 foreach 返回多个不同的数据帧
- reactjs - Webpack-dev-server 未检测到文件更改
- r - R - 为每一行提取一个字符串列:变量名和值 - 数据清理