WPF: How can I wrap items in an ItemsControl in a different template?
I have ItemsControl
one that contains elements, each with its own DataTemplate
. Each class ViewModel
in the ItemsSource derives from a common ancestor that has a property Header
.
I want to wrap each item in a control Expander
, but my problem is that I don't know how to wrap each DataTemplate in the DataContext of the expanding part of the Expander.
In the 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 just 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;
}
}
XAML windows:
<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 surprising, but understandable:
alt text http://img514.imageshack.us/img514/6937/itemscontrol.png
I really expect custom UserControls to appear in the extended sections ...
source to share