首页 > 解决方案 > 水平列表框多行(WPF)

问题描述

我想实现一个带有多行的水平列表框。

使用 WrapPanel:

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

我得到以下结果:

在此处输入图像描述

但我正在寻找这个结果:

在此处输入图像描述

我该如何实施?

标签: c#wpfxaml

解决方案


根据您的评论,UniformGrid每当调整窗口大小时,我都会调整行数/列数。

MainWindow.xaml:

<Grid x:Name="Container">
    <ListBox HorizontalContentAlignment="Stretch">
          <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid x:Name="ItemsGrid" Loaded="ItemsGrid_Loaded" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
</Grid>

名字和事件很重要。它们用于调整代码文件中的列/行。

主窗口.xaml.cs

public partial class MainWindow : Window
{
    private UniformGrid itemsGrid;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void ItemsGrid_Loaded(object sender, RoutedEventArgs e)
    {
        // Set reference and adjust columns/rows once the UniformGrid is loaded.
        itemsGrid = sender as UniformGrid;
        ((UniformGrid)sender).Columns = (int)(Container.ActualWidth / 250);
        ((UniformGrid)sender).Rows = (int)(Container.ActualHeight / 75);
    }

    private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        // Adjust number of columns/rows whenevner the window is resized.
        if (itemsGrid != null)
        {
            itemsGrid.Columns = (int)(Container.ActualWidth / 250);
            itemsGrid.Rows = (int)(Container.ActualHeight / 75);
        }
    }
}

这肯定可以清理一下,但它似乎可以完成这项工作。可能有更优雅的解决方案,但我找不到任何...


推荐阅读