I've got this UserControl defined in XAML and would like to set the ItemsPanelTemplate dynamically in my code behind class (not in the XAML like in the example):
<UserControl>
<ItemsControl x:Name="Items">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid> <!-- I want to add this Grid definition in code behind -->
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</UserControl>
I tried something like
this.Items.ItemsPanel.Template = new Grid();
but failed miserably. Any help?
Background: I only know the number of grid columns and rows at runtime.

You need to create an
ItemsPanelTemplateand set it'sVisualTreeto aFrameworkElementFactory(deprecated) which creates theGrid, or use theXamlReaderto parse a XAML-string which specifies the template.This question contains usage examples of both methods (albeit for a different template property).
An easier method to manipulate the panel at runtime is outlined in this question.