3
votes

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.

2
This works for me. Could you describe how it's going wrong? Are you seeing any binding errors in the Output window when you run it under the debugger?itowlson

2 Answers

1
votes

I finally had a chance to fight with this more and made it work. I had to delete the StaticResource, as it was interfering with setting the DataContext of the ProductSummaryControl. I still don't understand why, but deleting the resource allowed the binding to occur. I also had to point the DataContext to the Content property of the ContentPresenter owning the templated control.

<DataTemplate>
    <local:ProductSummaryControl DataContext="{TemplateBinding Content}" 
                                 HorizontalAlignment="Stretch"/>
</DataTemplate>
0
votes

Might be an issue with the way you structured your ProductSummaryControl, because even if you don't put {Binding} the DataContext will get automatically inherited to the control