Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Change an ItemsPanelTemplate in Code Behind?

Tags:

c#

.net

xaml

uwp

<ItemsControl>        
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

If I want to change the ItemsPanelTemplate from the default (StackPanel) to a Grid, I do the above in XAML. How could I achieve the same thing in code?

I read this here but couldn't figure it out.

like image 391
Sean O'Neil Avatar asked Oct 19 '25 14:10

Sean O'Neil


1 Answers

I'd prefer to do this in the default style of the custom control inside Generic.xaml, but if you want a pure C# way, here is how it can be done -

private void ApplyGridAsItemsPanel()
{
    MyItemsControl.ItemsPanel = ParseItemsPanelTemplate(typeof(Grid));

    ItemsPanelTemplate ParseItemsPanelTemplate(Type panelType)
    {
        var itemsPanelTemplateXaml =
            $@"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                                  xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                   <{panelType.Name} />
               </ItemsPanelTemplate>";

        return (ItemsPanelTemplate)XamlReader.Load(itemsPanelTemplateXaml);
    }
}
like image 93
Justin XL Avatar answered Oct 21 '25 02:10

Justin XL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!