使用来自其他 ViewModel 的 ObservableCollection 的数据填充 ComboBox
Fill ComboBox with data from ObservableCollection from other ViewModel
我在 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。它还应该自动更新所做的任何更改。
诀窍是在 ViewModel 1 中使用 ViewModel 2 作为参数。这样您就可以访问 ViewModel 2 中的 ObservableCollection Locations
ViewModel1
private ObservableCollection<Location> _allLocations;
public ObservableCollection<Location> AllLocations
{
get { return _allLocations; }
set { _allLocations = value; RaisePropertyChanged("AllLocations"); }
}
public ViewModel1(ViewModel2 vm2 )
{
AllLocations = vm2.Locations;
}
我在 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。它还应该自动更新所做的任何更改。
诀窍是在 ViewModel 1 中使用 ViewModel 2 作为参数。这样您就可以访问 ViewModel 2 中的 ObservableCollection Locations
ViewModel1
private ObservableCollection<Location> _allLocations;
public ObservableCollection<Location> AllLocations
{
get { return _allLocations; }
set { _allLocations = value; RaisePropertyChanged("AllLocations"); }
}
public ViewModel1(ViewModel2 vm2 )
{
AllLocations = vm2.Locations;
}