动态控件之ItemsPanelTemplate
一、Axaml生成
列表框有一个属性,其中包含一个用于布局列表项的模板控件。默认情况下,这是一个堆叠面板。为了使专辑封面填充所有空间,可以将面板模板更改为包装面板。方式如下:
<ListBox ItemsSource="{Binding SearchResults}" SelectedItem="{Binding SelectedAlbum}" Background="Transparent" Margin="0 20"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel /> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox>
这里是没有问题的,但是我的控件都是动态生成的,上边的xaml也想翻译成C# 动态生成代码。
二、C#动态生成
ListBox albumList = new ListBox { Background = Brushes.Transparent, Margin = new Thickness(0, 20) }; ItemsPanelTemplate itemsPanelTemplate = new ItemsPanelTemplate { Content = new WrapPanel() }; albumList.ItemsPanel = itemsPanelTemplate;
使用Content装载WrapPanel,是有问题的:
Unexpected content Avalonia.Controls.WrapPanel Arg_ParamName_Name
而只提供了ItemsPanelTemplate只提供了如下图的属性和方法:
因此就无法使用动态生成的方式了。
三、Axaml结合动态生成
既然整个axaml页面的控件都是动态生成,只有ListBox使用WrapPanel是报错,那么我们使用混合方式,该控件声明在axmal中写,在code-behind中使用,和其他动态生成的控件进行结合
axaml中:
<UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="Avalonia.MusicStore.Views.MusicStoreView"> <ListBox x:Name="_albumList" Background="Transparent" Margin="0 20"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel /> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> </UserControl>
code-behind中:
public MusicStoreView() { InitializeComponent();
//这里注释的是动态生成的其他控件,包含_mainDockPanel
AvaloniaXamlLoader.Load(this); // 加载XAML内容 ,这句代码非常重要,将axaml中的控件优先加载过来
_albumList.ItemsSource = this.GetAlbumViews();
_mainDockPanel.Children.Add(_albumList);
// 将DockPanel设置为UserControl的内容
this.Content = _mainDockPanel;
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!