如何在后面的代码中将ItemsPanelTemplate设置为动态创建的Grid

nab*_*lke 6 c# wpf xaml itemscontrol itemspaneltemplate

我已经UserControl定义了这个XAML并且想ItemsPanelTemplate在我的代码后面动态设置(XAML在示例中不是这样):

<UserControl>
    <ItemsControl x:Name="Items">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid> <!-- I want to add this Grid definition in code behind -->
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                    </Grid.RowDefinitions>
                </Grid>
            </ItemsPanelTemplate>
       </ItemsControl.ItemsPanel>
    </ItemsControl>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

我试过类似的东西

this.Items.ItemsPanel.Template = new Grid();
Run Code Online (Sandbox Code Playgroud)

但悲惨地失败了.有帮助吗?

背景: 我只知道运行时网格列和行的数量.

H.B*_*.B. 5

您需要创建ItemsPanelTemplate并将其设置为创建 的VisualTreea (已弃用) ,或使用来解析指定模板的 XAML 字符串。FrameworkElementFactoryGridXamlReader

这个问题包含这两种方法的使用示例(尽管针对不同的模板属性)。

这个问题概述了一种在运行时操作面板的更简单的方法。


小智 5

您可以通过在后面的代码中创建 MannualCode 来为所欲为: 1. 创建一个方法如下,它将返回一个 ItemsPanelTemplate

     private ItemsPanelTemplate GetItemsPanelTemplate()
    {
        string xaml = @"<ItemsPanelTemplate   xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition />
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition />
                                </Grid.RowDefinitions>
                            </Grid>
                    </ItemsPanelTemplate>";
        return XamlReader.Parse(xaml) as ItemsPanelTemplate;
    }
Run Code Online (Sandbox Code Playgroud)
  1. 现在将此模板添加到您的 Listbox ItemsPanel 中:

       MyListBox.ItemsPanel = GetItemsPanelTemplate();
    
    Run Code Online (Sandbox Code Playgroud)

这对我来说很好用。希望这会有所帮助。

继续编码....:)