gpt4 book ai didi

c# - 如何在代码隐藏中将 ItemsPanelTemplate 设置为动态创建的网格

转载 作者:太空狗 更新时间:2023-10-29 21:29:37 25 4
gpt4 key购买 nike

我在 XAML 中定义了这个 UserControl 并且想在我的代码隐藏类中动态设置 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>

我试过类似的东西

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

但惨遭失败。有帮助吗?

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

最佳答案

您可以通过在代码隐藏中创建 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;
}
  1. 现在将此模板添加到您的 Listbox ItemsPanel 中:

       MyListBox.ItemsPanel = GetItemsPanelTemplate();

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

继续编码....:)

关于c# - 如何在代码隐藏中将 ItemsPanelTemplate 设置为动态创建的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8398000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com