I have an ItemsControl that contains items that each has its own DataTemplate. Each ViewModel class in the ItemsSource derives from a common ancestor that has a Header property.
I want to wrap each item in a Expander control, but my problem is that I don’t know how to ‘carry over’ each ‘DataTemplate’ to the DataContext of the expading part of the Expander.
In code, my problem looks like this:
VieModels:
public class VM { public string Name { get; set; } }
public class VM1 : VM { public string Description { get; set; } }
public class VM2 : VM { public string Sakkie { get; set; } }
Items property on the code-behind (because it’s simple for the purpose of this question)
public IEnumerable<VM> Items
{
get
{
yield return new VM1() { Name = "First VM1", Description = "First VM1 Description" };
yield return new VM2() { Name = "Vm2, nr2", Sakkie = "sakkie sakkie boeredans" } ;
yield break;
}
}
The XAML of the window:
<Window.Resources>
<DataTemplate DataType="{x:Type local:VM1}">
<local:VM1UC />
</DataTemplate>
<DataTemplate DataType="{x:Type local:VM2}">
<local:VM2UC />
</DataTemplate>
<DataTemplate x:Key="DataTemplate1">
<Expander Header="{Binding Name}">
<ContentPresenter DataContext="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}"/>
</Expander>
</DataTemplate>
</Window.Resources>
<ItemsControl ItemsSource="{Binding Items}" Background="LightCoral" ItemTemplate="{DynamicResource DataTemplate1}"/>
It looks like this, which is suprising, but understandable:
alt text http://img514.imageshack.us/img514/6937/itemscontrol.png
I am actually expecting the custom UserControls to show up in the expanded sections…
Instead of setting the
DataContext, you should set theContent:This will ensure the appropriate
DataTemplateis resolved based on the type of theContent.