Is there any way to make a DataTemplate reference itself just from XAML? In this particular case trying to reference a DataTemplate from a ListBox contained within the same DataTemplate. Here is the solution I'd like, which doesn't work.
<DataTemplate x:Key="nestedItem" DataType="{x:Type local:NestedItem}">
<Expander Header="{Binding Path=Name}">
<ListBox ItemsSource="{Binding Path=Items}" x:Name="itemsList"
ItemTemplate="{StaticResource nestedItem}"/>
</Expander>
</DataTemplate>
And here's the solution I am currently using, which works.
<DataTemplate x:Key="nestedItem" DataType="{x:Type local:NestedItem}">
<Expander Header="{Binding Path=Name}" Expanded="OnItemExpanded">
<ListBox ItemsSource="{Binding Path=Items}" x:Name="itemsList"/>
</Expander>
</DataTemplate>
With code behind:
private void OnItemExpanded(object sender, RoutedEventArgs e)
{
if (e.OriginalSource != sender) return;
var source = (Expander) sender;
ListBox listBox = source.FindName("itemsList") as ListBox;
NestedItem item = source.DataContext as NestedItem;
listBox.ItemsSource = item.Items;
listBox.ItemTemplate = (DataTemplate) FindResource("nestedItem");
}