2014-07-18 68 views
0

這很難解釋,但我會盡我所能。我有一個包含兩個集合的ViewModel對象。WPF綁定兄弟收集到一個孩子ListBox控件

// populate the child1 and child 2 collections 
this.DataContext = ParentViewModel; 

在XAML代碼一切數據網格控制內部:

public class ParentViewModel 
{ 
    public ObservableCollection<Child1> ChildCollection1 {get;set;} 
    public ObservableCollection<Child2> ChildCollection2 { get;set; } 
} 

在XAML視圖文件,如下所示的DataContext設置。 DataGrid控件的ItemsSource被設置爲Child1Collection,因爲子對象具有一些需要在大多數數據網格列中顯示的字段。 DataGrid的其中一列是一個ListBox控件。我希望ListBox控件使用Child2Collection作爲ItemsSource。

我該怎麼做?

+1

看起來就像你有一個錯誤的視圖模型利用ElementNameRelativeResource

例如

的。從技術上講,一個'DataGrid'只需要一個集合,但是每個項目(在集合中)可能有另一個集合,...這意味着它取決於你希望如何爲ChildCollection1中的每個項目填充帶有ChildCollection2的'ListBox' '。 –

+0

我期待這個答案! :)我想我的藏品的每個項目都會有你建議的另一個藏品。謝謝! –

+1

ChildCollection2是否爲ChildCollection1的每個元素保存相同的值?發佈您將這個ListBox放入的DataGridTemplateColumn的xaml。您可以執行您正在嘗試執行的操作,但我希望看到您正在採取的方法來幫助您完成最後一步。 –

回答

1

您可以使用ElementName

<DataGrid x:Name="dGrid" 
      ItemsSource="{Binding ChildCollection1}"> 
    <DataGrid.Columns> 
     <DataGridTemplateColumn> 
      <DataGridTemplateColumn.CellTemplate> 
       <DataTemplate> 
        <ListBox ItemsSource="{Binding DataContext.ChildCollection2,ElementName=dGrid}" /> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellTemplate> 
     </DataGridTemplateColumn> 
    </DataGrid.Columns> 
</DataGrid> 

使用RelativeSource

<DataGrid ItemsSource="{Binding ChildCollection1}"> 
    <DataGrid.Columns> 
     <DataGridTemplateColumn> 
      <DataGridTemplateColumn.CellTemplate> 
       <DataTemplate> 
        <ListBox ItemsSource="{Binding DataContext.ChildCollection2,RelativeSource={RelativeSource FindAncestor,AncestorType=DataGrid}}" /> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellTemplate> 
     </DataGridTemplateColumn> 
    </DataGrid.Columns> 
</DataGrid>