如何在代码ItemsPanelTemplate设定为动态创建网格后面 [英] How to set ItemsPanelTemplate to a dynamically created Grid in code behind
问题描述
我这有用户控件
在 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屋!