I want to reuse my UserControls in other UserControls like page or window as DataTemplates, in this example inside a ListBox. Everything is MVVM.
I've a UserControl called "CardControl" to display a simple object "Card". Card has two Properties, "ID" and "CardImage". The controls DataContext is set via XAML. If I open this UserControl in VS or Blend it shows me the dummy Card that I have defined in the corresponding ViewModel.
Now I have another UserControl called "CardSetControl", which should display a collection of Cards. So the ViewModel has one property of type ObservableCollection<Card> called "Cards".
Here is the code:
<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 DataContext="{Binding "Current listbox item as DataContext of CardControl???"}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
After reading tons of articles about MVVM and DataContext/Binding I still didn't get it to work. How is this whole hierarchical USerControls/DataContexts thing done the best clean way?
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.