Search code examples
wpfitemscontrol

WPF ItemsControl and binding to self


I have an items control bound to a collection of type 'TypeA'. This type 'TypeA' has a collection of type 'TypeB'.

In the items control dataTemplate, I have a datagrid which displays a row for each item of the TypeB collection and for each row one column displaying the value of the variable 'VariableOfTypeB'.

It works fine.

Now, I would like to display another datagrid below which binds to the current item of the collection of type 'TypeA' and which would display the value of the variable 'VariableOfTypeA'. This I cannot seem to achieve.

I can access 'VariableOfTypeA' outside of the datagrid, in a label for instance.

Would you have any tip please?

<ItemsControl ItemsSource="{Binding TypeACollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
                <StackPanel>
                    <DataGrid ItemsSource="{Binding TypeBCollection}">
                        <DataGrid.Columns>
                            <DataGridTextColumn Width="Auto"
                                                Binding="{Binding VariableOfTypeB />
                        </DataGrid.Columns>
                    </DataGrid>
                    <!-- cannot make this work -->
                    <DataGrid ItemsSource="{Binding}">
                        <DataGrid.Columns>
                            <DataGridTextColumn Width="Auto"
                                                Binding="{Binding VariableOfTypeA />
                        </DataGrid.Columns>
                    </DataGrid>
                </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Solution

  • The ItemsControl does not have a SelectedItem which is what you are looking for in a sense.

    You would be better suited to use a DataGrid or ListView which has a selected row property (of/from your A collection) which then could be bound to in the subgrid to show the alternate information.