【发布时间】:2018-11-19 15:40:41
【问题描述】:
我有一个问题,关于如何在 WPF C# 的两个 ViewModel 中使用公共 ObservableCollection?
我有两个视图,第一个视图包含一个 observablecollection 以某种形式在组合框中使用的类别。第二个视图是一个允许添加、编辑和删除类别的窗口。现在我分别检索两个视图的类别,但我想组合并使用一个通用的可观察集合,以便在第二个视图中添加、更改或删除类别时获得新的更改。
视图和视图模型都由主视图模型控制:
public viewModel1 viewModel1 { get; set; }
public ViewModel2 ViewModel2 { get; set; }
public MainViewModel()
{
this.InitializeCommands();
this.viewModel1 = new viewModel1();
this.ViewModel2 = new ViewModel2();
this.ViewModel2.OnChangedCategory += (s, e) =>
{
this.viewModel1.Categories = GetCategories();
};
}
View1 的视图模型:
public ObservableCollection<Categories> GetCategories
{
get
{
if (this._getCategories == null)
{
this._getCategories = methods.GetCategories();
}
return this._getCategories ;
}
set
{
if (this._getCategories != value)
{
this._getCategories = value;
this.OnPropertyChanged("GetCategories");
}
}
}
View2 的视图模型:
public ObservableCollection<Categories> GetCategories
{
get
{
if (this._getCategories == null)
{
this._getCategories = methods.GetCategories();
}
return this._getCategories ;
}
set
{
if (this._getCategories != value)
{
this._getCategories = value;
this.OnPropertyChanged("GetCategories");
}
}
}
理论上,它们都是相同的,只是两个视图模型中的两个不同的可观察集合,我想在两个视图中使用相同的可观察集合,如果它在第一个或第二个 ViewModel 中没有关系。但如果它在 viewmodel 2 中可能更有意义。假设我决定在 ViewModel 2 中有一个通用类别的可观察集合,那么 Viewmodel 1 如何使用来自 ViewModel 2 的这个可观察集合并且仍然在更改时保持同步?
我该怎么做?
【问题讨论】:
-
为数据创建一个模型类并将其交给两个视图模型
-
创建基类来处理它
-
@nicolas 更新类会更新两个视图模型吗?
-
View 的 DataContext 是设置为 MainViewModel.ViewModel1 和 MainViewModel.ViewModel2 还是直接设置为单个 ViewModel?你能不能在 MainViewModel 中没有 ObservableCollection 并绑定到它?
-
@Fredrik Linger 如果模型类公开了一个保存数据的属性并且两个视图模型都引用了这个属性,那么它们都使用相同的数据(例如
ObservableCollection),这意味着如果其中一个进行更改,所有人都“看到”更改(并在ObservableCollection案例中得到通知)