【问题标题】:Horizontal ListBox multiple lines (WPF)水平列表框多行(WPF)
【发布时间】:2020-01-21 04:45:03
【问题描述】:

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

使用 WrapPanel:

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

我得到以下结果:

但我正在寻找这个结果:

我该如何实现?

【问题讨论】:

  • 你试过UniformGrid而不是StackPanel吗?
  • @SomeBody 是的,但使用 UniformGrid 我无法定义 MinWidth

标签: c# wpf xaml


【解决方案1】:

根据您的 cmets,我制作了一个 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>

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

MainWindow.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);
        }
    }
}

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

【讨论】:

  • 我没有按照你说的做,因为我想让列数自动调整到ListBox的宽度。
  • 希望通过这张图可以理解:i.imgur.com/pV8ZLAw.png
  • 谢谢,我实现了你的想法,这就是我想要的。我在使用 UniformGrid 时遇到的唯一问题是,通过更改窗口的垂直大小,每个项目的高度都会发生变化,并且会导致垂直滚动条出错。
猜你喜欢
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
相关资源
最近更新 更多