【问题标题】:Fill ComboBox with data from ObservableCollection from other ViewModel使用来自其他 ViewModel 的 ObservableCollection 的数据填充 ComboBox
【发布时间】: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


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2016-01-20
    • 2013-05-11
    • 2014-09-22
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多