Reputation: 1228
I cannot bind to a DataTemplate
from within another DataTemplate
, is this due to the data source not being present at runtime?
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<DataTemplate x:Key="Employees">
<StackPanel>
<ListView ItemsSource="{Binding Path=Employees}">
<ListView.View>
<GridView>
<GridViewColumn Header="FirstName">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding FirstName}"/>
</DockPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="LastName">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding LastName}"/>
</DockPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="Company">
<StackPanel>
<TextBlock>Company data</TextBlock>
<ListView
<!-- Bind current data source -->
ItemsSource="{Binding}"
<!-- Static resource (nested template) -->
ItemTemplate="{StaticResource Employees}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<StackPanel>
<TextBlock>Companies:</TextBlock>
<ListView ItemsSource="{Binding Companies}" ItemTemplate="{StaticResource Company}" />
</StackPanel>
</Page>
I am trying to make the employees DataTemplate
reusable as it will be useful to reference in other data DataTemplate
s. Is there something wrong with the binding in the Company DataTemplate
: <ListView ItemsSource="{Binding}" ItemTeplate="{StaticResource Employees}" />
Why won't Employees bind?
Upvotes: 1
Views: 3013
Reputation: 136663
Worked for me. Has the DataContext been set ? That tripped me up while I was trying this out.
Xaml
<StackPanel>
<StackPanel.Resources>
<DataTemplate x:Key="_Chest">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding WeightInKgs, StringFormat=Contains \{0\} kgs of : }"/>
<TextBlock Text="{Binding Contents}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="_Gallery">
<ListBox ItemsSource="{Binding}" ItemTemplate="{StaticResource _Chest}" Background="Aqua"/>
</DataTemplate>
</StackPanel.Resources>
<ContentControl Content="{Binding Treasures}" ContentTemplate="{StaticResource _Gallery}" Background="Coral"/>
</StackPanel>
Code Behind
public MainWindow()
{
InitializeComponent();
Treasures = new List<Chest>{new Chest{Contents = "Gems", WeightInKgs=10},
new Chest{Contents = "Gold", WeightInKgs= 25}};
this.DataContext = this;
}
public List<Chest> Treasures { get; set; }
Upvotes: 4