I have a simple class Product and a UserControl named ProductSummaryControl. ProductSummaryControl displays the details for a Product class that is passed in to its DataContext. I have verified that this works when I set up the control and its property manually.
I run into a problem when I try to use the ProductSummaryControl as part of a ListBox ItemTemplate. This is the relevant code:
<ListBox x:Name="ProductsList" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<local:ProductSummaryControl DataContext="{Binding}" HorizontalAlignment="Stretch"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I set the ListBox ItemsSource to a List and I see multiple instances of my ProductSummaryControl that correspond to the number of products in the list, but the controls are not properly bound to the data. All of the examples I've found of customizing ItemTemplate on the web suggest that {Binding} is the correct way to get the item value, but I'm apparently missing something...
UPDATE:
I did a bit more research and I've discovered that the DataContext of the ProductSummaryControl is being set to a default instance of Product(). I think this is because of this:
<UserControl.Resources>
<DBSchmid_Data:Product x:Key="ProductDataSource" d:IsDataSource="True"/>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Mode="OneWay" Source="{StaticResource ProductDataSource}"/>
</UserControl.DataContext>
This was caused by setting up the UserControl's DataContext in Blend so that the various elements in the control could reference properties of the inherited DataContext. I verified that I could change the value of DataContext from a button click method and have the binding work properly, so I thought it would also work with binding through a template. Apparently the two cases are treated differently, but I still don't understand how.