2013-01-23 3 views
0

각 뷰 모델에 관찰 가능 콜렉션이있는 두 개의 뷰 모델이 있습니다. 이 컬렉션에는 서로 관계가 있습니다. 예를 들어, 하나는 ID와 이름을 가진 ClassA의 컬렉션이고, 다른 하나는 ClassAId와 일부 OtherValue가있는 ClassB의 컬렉션입니다. CollectionA의 각 항목에 대해 ListAut로 데이터 바인딩 할 수 있습니까? OtherValue 내가 당신이 최선의 선택이 형성되고 새 컬렉션을 반환하는 것입니다있어 내 질문 :두 뷰 모델의 데이터 목록보기

+0

실제로 해 보았습니까? 무슨 일이야? – RhysW

+0

다른 datacontext에서 CollectionB 바인딩을 얻는 방법을 모르겠습니다. – Peter

+0

그래서 A와 B를 모두 포함하는 래퍼가 필요하며이를 항목 소스로 사용합니까? – RhysW

답변

1

의 내 설명과 함께 많은 당신을 혼동하지 않았다 희망 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> 

에서 페치 해당 컬렉션에 특수화 된 새로운 뷰 모델 (또는 모델)을 기반으로 한 뷰 모델 수준 :

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

관련 문제