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.
我有一个ItemsControl,其中包含每个都有自己的DataTemplate的项目。 ItemsSource中的每个ViewModel类都派生自一个具有Header属性的共同祖先。
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.
我想将每个项目包装在Expander控件中,但我的问题是我不知道如何将每个'DataTemplate''转移'到Expander的expading部分的DataContext。
In code, my problem looks like this:
在代码中,我的问题看起来像这样:
VieModels:
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:
窗口的XAML:
<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
alt text http://img514.imageshack.us/img514/6937/itemscontrol.png
I am actually expecting the custom UserControls to show up in the expanded sections...
我实际上期望自定义的UserControls显示在扩展的部分中......
1 个解决方案
#1
4
Instead of setting the DataContext
, you should set the Content
:
您应该设置内容,而不是设置DataContext:
<ContentPresenter Content="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}"/>
This will ensure the appropriate DataTemplate
is resolved based on the type of the Content
.
这将确保根据内容的类型解析相应的DataTemplate。
#1
4
Instead of setting the DataContext
, you should set the Content
:
您应该设置内容,而不是设置DataContext:
<ContentPresenter Content="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}"/>
This will ensure the appropriate DataTemplate
is resolved based on the type of the Content
.
这将确保根据内容的类型解析相应的DataTemplate。