<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
如果要将ItemsPanelTemplate从默认(StackPanel)更改为Grid,请在XAML中执行上述操作。如何在代码中实现相同的目的?
我更喜欢使用Generic.xaml中自定义控件的默认样式来执行此操作,但是如果您希望使用纯C#方式,可以按以下步骤进行:
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);
}
}
Run Code Online (Sandbox Code Playgroud)