<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
如果我想将 ItemsPanelTemplate 从默认 (StackPanel) 更改为 Grid,我在 XAML 中执行上述操作。我怎样才能在代码中实现相同的目的?
我读了这个here但想不通。
最佳答案
我更喜欢在 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);
}
}
关于c# - 如何在代码隐藏中更改 ItemsPanelTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555462/