动态控件之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 @ 2024-03-22 11:15  搬砖滴  阅读(64)  评论(0编辑  收藏  举报