0

I'm trying to bind a ObservableCollection of a class to a combo box inside a datagrid.

public class ProductContainer
{
    public string Product { get; set; }
    public List<string> SubProducts { get; set; }

    public ProductContainer()
    {
        SubProducts = new List<string>();
    }
}

In my MainWindow.xaml i have the list.

public ObservableCollection<ProductContainer> Products { get; set; }

I'm trying to add it to a combo box to a datagrid with what i have, but it's not binding properly. What would the xaml look like?


<DataGrid AutoGenerateColumns="False" Name="ProductGrid" Width="Auto"
          AlternatingRowBackground="LightSlateGray" SelectionMode="Single" SelectionUnit="FullRow"  CanUserAddRows="True" CanUserDeleteRows="True" CurrentCellChanged="ProductGrid_CurrentCellChanged">
    <DataGrid.Resources>
        <DataTemplate x:Key="editProductTemplate">
            <ComboBox x:Name="cbProducts" ItemsSource="{Binding Path=Products, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" SelectedItem="{Binding Product}" SelectedValuePath="Product" DisplayMemberPath="Product"/>
        </DataTemplate>
        <DataTemplate x:Key="editSubProductTemplate">
            <ComboBox ItemsSource="{Binding Product.SubProducts, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTemplateColumn MinWidth="120"
            Header="Product"              
            CellTemplate="{StaticResource editProductTemplate}" />
        <DataGridTemplateColumn MinWidth="120"
            Header="SubProduct"                          
            CellTemplate="{StaticResource editSubProductTemplate}"/>
    </DataGrid.Columns>
</DataGrid>

This the xaml for it. The first combo box populates but the second one never populates based on whats in the first one, or shows anything at all.

H.B.
  • 166,899
  • 29
  • 327
  • 400
jspence
  • 409
  • 4
  • 13

1 Answers1

1

Depends on the DataContexts. For info on how to debug bindings see MSDN, that is always useful and there are related questions which may help you both in constructing the right binding and avoiding ones that fail:


The path in your second ComboBox.ItemsSource should probably just be SubProducts as your object's Product property is just a string. Further your classes should implement INotifyPropertyChanged so that the UI can be notified of any changes.

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400