Search code examples
wpfdata-bindingbindingmaster-detail

How does WPF Binding navigate relationships?


I'm trying to implement a master-detail relationship in the following way:

(shown in a ComboBox)                       (shown in a DataGrid)
|-----------|                               |------------|
| Customers |                               | Orders     |
|-----------|                               |------------|
| Id        |--- CustomersOrdersRelation ---| CustomerId |
| Name      |                               | OrderId    |
| ...       |                               | ...        |
|-----------|                               |------------|

But I also have an <All Customers> item in the combobox, for which I need to see all orders from all customers displayed in the details datagrid.

Here's a snippet of the XAML code:

<ComboBox x:Name="CustomersComboBox" ...>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="{StaticResource nullCustomer}" /> <!-- I wrote my own class NullCustomer -->
            <CollectionContainer Collection="{Binding Source={StaticResource CustomersCollectionViewSource}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

<DataGrid ItemsSource="{Binding ElementName=CustomersComboBox, Path=SelectedItem.CustomersOrdersRelation}" ...>

Now I've got two questions:

  1. How does the Binding in the datagrid find Path=SelectedItem.CustomersOrdersRelation when combobox's SelectedItem (which is a DataRowView at runtime) doesn't have a property CustomersOrdersRelation?

  2. What is the simplest way for me to modify my own NullCustomer class so that when I select <All Customers> I'll have the results of AllOrdersCollectionViewSource displayed?


Solution

    1. DataRowView implements ICustomTypeDescriptor, which probably is used by the binding system to determine how to get that property.

    2. Also give it a property CustomersOrdersRelation which returns a CompositeCollection containing CollectionContainers for all the orders of the customers.