2013-01-23 58 views
0

我有两个viewmodels在每个视图模型中有一个observablecollection。 这些集合有相互关系。 例如,假设一个是具有Id和Name的ClassA的集合,另一个是具有ClassAId和一些OtherValue的ClassB的集合是否可以将这些数据绑定到ListView,以便对于CollectionA中的每个项目OtherValue是CollectionB与来自两个视图模型的数据的列表视图

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

牵强我希望我没有混淆你得多跟我,我的问题:)

+0

你真的尝试过吗?怎么了? – RhysW

+0

我不知道如何获得CollectionB绑定,因为它在其他数据环境中 – Peter

+0

因此,您需要一个包含A和B的包装,然后将其用作项目源? – RhysW

回答

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<T>与否,就看你是否需要此集合可观察到。
  • 您还可以展开您的视图模型以订阅ClassAClassB集合,以便在它们中的任何一个更改时更新您的主集合。

无论哪种方式,这应该给你一个很好的想法,进行一些小的调整,以适应你的代码。

+0

我会试试这个 – Peter

相关问题