UserControl as DataTemplate inside ListBox

For the ListBox control an inferred ListBoxItem is created for each item in the items source. The Item is set as the DataContext and your ItemTemplate is set as the template. Since DataContext inherits, you don't have to explicitly set it because it's already the instance of Card in your DataTemplate.

For this case, you don't have to set the DC on the CardControl because it's set for you.

<ListBox x:Name="MyList" ItemsSource="{Binding CardSet.Cards}"> 
  <ListBox.ItemTemplate> 
    <DataTemplate> 
      <StackPanel> 

        <!-- WORKING, but not what i want --> 
        <TextBlock Text="{Binding ID}" /> // would display ID of Card 
        <Image Source="{Binding Image}" /> // would display Image of Card 

        <!-- NOT WORKING, but this is how i want it to work --> 
        <UserControls:CardControl /> 

      </StackPanel> 
    </DataTemplate> 
  </ListBox.ItemTemplate> 
</ListBox> 

Should work for you.


In your example, the DataContext of the UserControl would be the currently selected Card. It flows into the UserControl and its child controls like any other UIElement receives the DataContext of its parent control.

This would work:

<ListBox x:Name="MyList" ItemsSource="{Binding CardSet.Cards}">
  <ListBox.ItemTemplate>
    <DataTemplate>
        <UserControls:CardControl />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Where CardControl is:

<UserControl x:Class="MySolution.CardControl" 
             OtherProperties="Not shown to keep this example small">
      <StackPanel>
        <TextBlock Text="{Binding ID}" /> 
        <Image Source="{Binding Image}" />
      </StackPanel>
</UserControl>