动态控件之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;
复制代码

 



如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
posted @   搬砖滴  阅读(94)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示