如何在代码ItemsPanelTemplate设定为动态创建网格后面 [英] How to set ItemsPanelTemplate to a dynamically created Grid in code behind

查看:171
本文介绍了如何在代码ItemsPanelTemplate设定为动态创建网格后面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这有用户控件 XAML 定义,并想将 ItemsPanelTemplate 动态地隐藏类我的代码(不是在 XAML 比如上例中):

I've got this UserControl defined in XAML and would like to set the ItemsPanelTemplate dynamically in my code behind class (not in the XAML like in the example):

<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>



我想是这样

I tried something like

this.Items.ItemsPanel.Template = new Grid();



而悲惨地失败了。任何帮助

but failed miserably. Any help?

背景:
我只知道在运行时网格列和行数

Background: I only know the number of grid columns and rows at runtime.

推荐答案

您需要创建一个 ItemsPanelTemplate 并设置它的的VisualTree 来一个 FrameworkElementFactory (不建议使用),它创建电网,或使用的 XamlReader 来的解析一个XAML字符串,它指定的模板。

You need to create an ItemsPanelTemplate and set it's VisualTree to a FrameworkElementFactory (deprecated) which creates the Grid, or use the XamlReader to parse a XAML-string which specifies the template.

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

This question contains usage examples of both methods (albeit for a different template property).

这是更简单的方法来处理在运行时面板的这个问题

An easier method to manipulate the panel at runtime is outlined in this question.

这篇关于如何在代码ItemsPanelTemplate设定为动态创建网格后面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆