【问题标题】:Listview with data from two viewmodels包含来自两个视图模型的数据的列表视图
【发布时间】:2013-01-23 11:32:23
【问题描述】:

我有两个视图模型,每个视图模型中都有一个 observablecollection。 这些集合相互关联。 例如,假设一个是具有 Id 和 Name 的 ClassA 的集合,另一个是具有 ClassAId 和一些 OtherValue 的 ClassB 的集合 是否可以将这些数据绑定到 ListView,以便从 CollectionB 中获取 CollectionA 中的每个项目的 OtherValue

   <ListView ItemsSource="{Binding ViewModelA.CollectionClassA}">
       <ListView.View>
          <GridView>                            
            <GridViewColumn DisplayMemberBinding="{Binding Path=ClassA.Name}"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=ClassB.OtherValue}"/>
          </GridView>
         </ListView.View>
    </ListView>

我希望我对我的问题的解释没有让你很困惑:)

【问题讨论】:

  • 你真的尝试过吗?会发生什么?
  • 我不知道如何获取 CollectionB 绑定,因为它在其他数据上下文中
  • 那么您需要一个包含 A 和 B 的包装器,然后将其用作项目源?
  • 我想我正在寻找类似的东西,因为我们两个来源似乎不可能
  • 是的,它们被设计为只接受一个来源,所以显而易见的解决方案是将它们放在一个对象中并传递它:)

标签: c# wpf mvvm


【解决方案1】:

您最好的选择是返回一个在视图模型级别形成的新集合,该集合基于该集合特有的新视图模型(或模型):

public class OtherViewModel
{
    //Expand these if you want to make it INPC
    public int Id { get; private set; }
    public string Name { get; private set; }
    public Foo OtherValue { get; private set; }
}

public class MainViewModel
{
    // Somewhere in MainViewModel, create the collection
    ObservableCollection<OtherViewModel> CreateCollection(ICollection<ClassA> a, ICollection<ClassB> b)
    {
        var mix = a.Join(b, a => a.Id, b => b.Id,
            (a, b) => new OtherViewModel { Id = a.Id, Name = a.Name, OtherValue = b.OtherValue });

        return new ObservableCollection<OtherViewModel>(mix);
    }

    // Expose the collection (possibly INPC if needed)
    public ObservableCollection<OtherViewModel> MixedCollection { get; private set; }
}

XAML:

<!-- Assuming the DataContext is MainViewModel -->
<ListView ItemsSource="{Binding MixedCollection}">
  <ListView.View>
    <GridView>                            
      <GridViewColumn DisplayMemberBinding="{Binding Path=Name}"/>
      <GridViewColumn DisplayMemberBinding="{Binding Path=OtherValue}"/>
    </GridView>
  </ListView.View>
</ListView>

注意事项:

  • 您可以选择是否使用ObservableCollection&lt;T&gt;,这取决于您是否需要可观察此集合。
  • 您还可以扩展视图模型以订阅 ClassAClassB 集合,以便在它们中的任何一个发生更改时更新您的主集合。

无论哪种方式,这应该让您对前进的方向有一个很好的了解,并进行一些小的调整以适应您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多