WPF C#如何在两个ViewModel中使用一个通用的ObservableCollection



我有一个问题,关于如何在WPF C#中的两个ViewModel中使用公共的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:的ViewModel

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的ViewModel:

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");
}
}
}

理论上,它们都是相同的,只是两个视图模型中的两个不同的可观察集合,我想在两个视图中使用相同的可观察集,如果它在第一个或第二个视图中并不重要。但如果它在视图模型2中,可能会更有意义。假设我决定在ViewModel 2中有一个通用类别的可观察集合,那么ViewModel 1如何使用ViewModel 2中的这个可观察集合并在更改时保持同步?

我该怎么做?

您可以将其作为资源,然后任何代码都可以访问它。与本文相关的示例有两对用户控件,它们共享两个这样的集合,听起来与您的需求非常相似。

https://social.technet.microsoft.com/wiki/contents/articles/29859.wpf-tips-bind-to-current-item-of-collection.aspx

最新更新