使用来自其他ViewModel的ObservableCollection中的数据填充ComboBox

时间:2015-07-25 21:02:34

标签: c# wpf mvvm combobox observablecollection

我在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中使用此集合与ComboBox绑定

private ObservableCollection<Location> _locations = new ObservableCollection<Location>();
public ObservableCollection<Location> Locations //Binds with the listbox
{
    get { return _locations; }
    set { _locations = value; }
}

如何从ViewModel2获取ObservableCollection到ViewModel1。它还应该自动更新已经进行的任何更改。

1 个答案:

答案 0 :(得分:-1)

使用ViewModel2作为ViewModel1中的参数是什么诀窍。这样,您就可以访问ViewModel 2中的ObservableCollection位置

ViewModel1

private ObservableCollection<Location> _allLocations;
public ObservableCollection<Location> AllLocations
{
    get { return _allLocations; }
    set { _allLocations = value; RaisePropertyChanged("AllLocations"); }
}

public ViewModel1(ViewModel2 vm2 )
{

    AllLocations = vm2.Locations;
}