如何在后面的代码中更改ItemsPanelTemplate?

Sea*_*eil 1 .net c# xaml uwp

<ItemsControl>        
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

如果要将ItemsPanelTemplate从默认(StackPanel)更改为Grid,请在XAML中执行上述操作。如何在代码中实现相同的目的?

在这里读过此书,但无法弄清楚。

Jus*_* XL 5

我更喜欢使用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)

  • 谢谢。我了解这是不合常规的,我很有可能会接受该建议。我没有意识到这会在c#文件中涉及实际的xaml语法,我认为这很荒谬。 (2认同)