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

You can do as you want by creating MannualCode in code behind as: 1. Create a Method as following which will return a ItemsPanelTemplate

     private ItemsPanelTemplate GetItemsPanelTemplate()
    {
        string xaml = @"<ItemsPanelTemplate   xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition />
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition />
                                </Grid.RowDefinitions>
                            </Grid>
                    </ItemsPanelTemplate>";
        return XamlReader.Parse(xaml) as ItemsPanelTemplate;
    }
  1. Now add this template in your Listbox ItemsPanel as:

       MyListBox.ItemsPanel = GetItemsPanelTemplate();
    

This is working fine for me. Hope this will help.

Keep Coding....:)


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.