0
votes

This is little hard to explain but I will try my best. I have a ViewModel object which contains two collections.

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

In the XAML view file the datacontext is set as shown below:

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

In the XAML code everything is inside the DataGrid control. The ItemsSource for the DataGrid control is set as Child1Collection since the child objects has some fields that needed to be shown in most of the datagrid columns. In one of the columns of the DataGrid is a ListBox control. I want that ListBox control to use Child2Collection as ItemsSource.

How can I do that?

1
looks like you have a wrong viewmodel. Technically a DataGrid needs just 1 collection, however each item (in the collection) may have another collection, ... That means it depends on how you want to fill the ListBox with ChildCollection2 for each item in ChildCollection1. - King King
I was expecting this answer! :) I guess each item of my collection will have another collection as you have advised. Thanks! - john doe
Is the ChildCollection2 going to hold the same values for each element of ChildCollection1? Post the xaml for the DataGridTemplateColumn you were putting this ListBox in. You can do what you were trying to do but I want to see the approach you were taking to help you take that last step. - Lee O.

1 Answers

1
votes

you can make use of ElementName or RelativeResource

example

using 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>

using 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>