【发布时间】:2015-10-16 08:09:52
【问题描述】:
我在 ViewModel1 中有一个 ComboBox,我需要填充它并使用另一个 ViewModel2 中的列表对其进行更新
XAML
<ComboBox ItemsSource="{Binding AllLocations}"/>
ViewModel1
private ObservableCollection<Location> _allLocations = new ObservableCollection<Location>();
public ObservableCollection<Location> AllLocations
{
get { return _allLocations; }
set { _allLocations = value; RaisePropertyChanged("AllLocations"); }
}
ViewModel2(我想在 ViewModel1 中使用这个 Collection 来绑定 ComboBox
private ObservableCollection<Location> _locations = new ObservableCollection<Location>();
public ObservableCollection<Location> Locations //Binds with the listbox
{
get { return _locations; }
set { _locations = value; }
}
如何将 ObservableCollection 从 ViewModel2 获取到 ViewModel1。它还应该自动更新所做的任何更改。
【问题讨论】:
-
ViewModel2 实例在哪里?它是 ViewModel1 的属性吗? ViewModel1 如何访问 ViewModel2 实例?
-
这是 2 个不同的视图模型,彼此不交互。我需要从 ViewModel2 访问 ObservableCollection 以填充组合框。
-
您希望对 Locations ObservableCollection 所做的更改应用于 AllLocation 集合吗?
-
通过在 ViewModel1 构造函数中将 ViewModel2 作为参数传递来找到解决方案
标签: c# wpf mvvm combobox observablecollection