如何在代码隐藏中更改ItemsPanelTemplate?

时间:2017-06-14 22:05:13

标签: c# .net xaml uwp

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

如果我想将ItemsPanelTemplate从默认(StackPanel)更改为Grid,我在XAML中执行上述操作。我怎么能在代码中实现同样的东西?

我读了这个here,但无法理解。

1 个答案:

答案 0 :(得分:5)

我更喜欢在 Generic.xaml 中的自定义控件的默认样式中执行此操作,但如果您想要纯C#方式,则可以采用以下方式完成此操作 - < / p>

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);
    }
}
相关问题