【问题标题】:fill ComboBox with items from different ViewModel用来自不同 ViewModel 的项目填充 ComboBox
【发布时间】:2016-01-20 01:42:57
【问题描述】:

我有一个绑定到 DataContext SceneViewModel 的 ComboBox,但我想用来自另一个名为 GearViewModel 的 ViewModel 的 observableCollection 中的数据填充它。 我该怎么做呢?或者这可能吗?

这里是 xaml

<UserControl x:Class="MoviePrepper.View.SceneView"
 DataContext="{Binding SceneViewModel, Source={StaticResource Locator}}">

<Grid>
    <ComboBox ItemsSource="{Binding to observableCollection in GearViewModel}}" SelectedItem="{Binding SceneCollectionView/Equipment, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</UserControl>

【问题讨论】:

  • 您是否需要将您的ComboBox 绑定到两个ObservableCollection(一个在SceneViewModel,另一个在GearViewModel)?或者只是将项目绑定到GearViewModel ObservableCollection?
  • 绑定到 GearViewModel ObservableCollection 中的项目
  • 所以如果你想以正确的方式使用MVVM,你需要在你的SceneViewModel中有一个GearViewModel
  • 我该如何以正确的方式做到这一点?我试过这个: var fillComboBox = new GearViewModel(); items= fillComboBox.FillGearComboBox();项目返回 null。

标签: c# wpf mvvm combobox viewmodel


【解决方案1】:

您可以使用这样的绑定来实现这一点:

<ComboBox ItemsSource="{Binding GearViewModel.MyCollection, Source={StaticResource Locator}}" 
          SelectedItem="{Binding Equipment, UpdateSourceTrigger=PropertyChanged}"/>

其中ItemsSource 属性绑定到Locator 中的GearViewModel.MyCollection 属性,SelectedItem 绑定到SceneViewModel.Equipment(由UserControl 的DataContext 设置)。

目前还不清楚您想在SelectedItem 属性上绑定什么属性,所以我做了一些假设。

Anywho,应该可以解决将您的 ItemsSource 属性绑定到不同视图模型的问题。

【讨论】:

    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 2016-03-23
    • 2023-03-19
    • 2010-10-26
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多