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
ItemsPanelTemplate
and set it'sVisualTree
to aFrameworkElementFactory
(deprecated) which creates theGrid
, or use theXamlReader
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.
Here's a XAML based program which uses
ItemsPanelTemplate
with aGrid
:MainWindow.xaml
:MainWindow.xaml.cs
:It's a simple text editor with a status bar:
Here's the equivalent program with the code in C# instead of XAML:
MainWindow.xaml
:MainWindow.xaml.cs
:The C# version is much more verbose. However, with the help of some extension methods, it can be written in a fluent style, eliminating the intermediate variables:
Here are the extension methods used:
You can do as you want by creating MannualCode in code behind as: 1. Create a Method as following which will return a ItemsPanelTemplate
Now add this template in your Listbox ItemsPanel as:
This is working fine for me. Hope this will help.
Keep Coding....:)
In case that you still have some work to do with the elements, you should take the following (extended) code:
First we need a helper in order to get the element:
Now we create the Panel (or something):