Search code examples
wpfuser-controlswpf-controlsdatatemplate

Use a user control as a DataTemplate within a WPF application


I am trying to create a user control within a WPF application that will serve as a DataTemplate for a ListBoxItem. The user control a grid with 4 TextBlocks. This control also contains other shapes and images more for visual aid than anything so I am omitting them from the code in this question for clarity.

When I drop the user control on my mainwindow.xaml I can see the control and the properly bound fields point to the first record in the datasource. What I want to do is have this control render repeatedly within either a listbox or a wrap panel for each record within the database.

Can anyone provide me with a pointer or sample of how to have a user control render as a DataTemplate within the ListBox control/other panel.

Up to this point I have tried the following with no avail: Thanks in advance for any tips.

<!--within Window.Resource -->
<DataTemplate x:Key="myActivity">
        <local:ucActivityItm /> <!--usercontrol -->
</DataTemplate>

<!-- Listbox within the window -->
<ListBox HorizontalAlignment="Stretch" ItemTemplate="{DynamicResource myActivity}"  VerticalAlignment="Stretch">
 <ListBoxItem>
<!-- control also added for testing to ensure it rendered out-->
<local:ucActivityItm />   
</ListBoxItem>        
</ListBox>

Solution

  • That DataTemplate isn't actually being assigned to your ListBox. There's three ways:

    1: Replace the template in the Resources section with

    <ListBox.ItemTemplate>
        <DataTemplate>
            <local:ucActivityItm />
        </DataTemplate>
    </ListBox.ItemTemplate>
    

    in the ListBox.
    2: Somewhat related:

    <ListBox ... ItemTemplate="{StaticResource myActivity}">
    

    3: Set the DataType parameter of the DataTemplate above to whatever the content of your ListBox is.

    <DataTemplate x:Key="myActivity" DataType="{x:Type ...}">
    

    I usually just do the first, but any should work.