I have a Recipe model that contains IList RecipeLineItems property. A single RecipeLineItem model has an Ingredient model property.
I created an AddRecipeViewModel for entering and saving a new Recipe instance. AddRecipeViewModel has a Recipe property that exposes a new Recipe instance. AddRecipeViewModel also has an ObservableCollection IngredientList that's used to select an Ingredient when adding a RecipeLineItem to Recipe (binding to this is my problem, as I will go on to describe). I have an AddRecipeView which presents my AddRecipeViewModel in a user control.
Here's my problem XAML from AddRecipeView:
<DataGrid Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Recipe.RecipeLineItems}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Ingredient" SelectedItemBinding="{Binding Ingredient}" DisplayMemberPath="{Binding Ingredient.Title}"
<!--
This doesn't work! I can't bind to the IngredientList property of my ViewModel!
-->
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:AddRecipeViewModel}}, Path=IngredientList}"/>
<!--
This works!
-->
<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}"/>
</DataGrid.Columns>
</DataGrid>
<!--
This also works!
-->
<ListBox Grid.Row="3" Grid.ColumnSpan="2"
ItemsSource="{Binding IngredientList}" DisplayMemberPath="{Binding Ingredient.Title}"/>
I can't figure out how to set the ItemsSource for my DataGridComboBoxColumn for the user to choose an Ingredient when adding a RecipeLineItem to Recipe. I've tried RelativeSource Self, etc to no avail. I'd be grateful for anyone's educated guess on how to make this work!
I have a temporary solution: rather getting an Ingredient list from AddRecipeViewModel, I created a static class for retrieving Ingredients and I added it to my User Control as a StaticResource. I then set my DataGridComboBoxColumn's ItemSource="{Binding myObjectProviderIngredientList" and it works. I'd much rather have my ViewModel provide this list, however.