Search code examples
c#wpfxamlitemscontrolitemspaneltemplate

How to set ItemsPanelTemplate to a dynamically created Grid in code behind


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.


Solution

  • You need to create an ItemsPanelTemplate and set it's VisualTree to a FrameworkElementFactory (deprecated) which creates the Grid, or use the XamlReader to 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.