<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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With