【问题标题】:How to make WrapPanel items line by line?如何逐行制作 WrapPanel 项目?
【发布时间】:2017-04-04 10:07:41
【问题描述】:

我有带有图标的WrapPanel。 我想逐行创建它(每行 5 个项目)。

所以,我的代码:

<WrapPanel Grid.Row="3"
        Grid.RowSpan="2"
        Grid.Column="4"
        x:Name="wpIcons">
</WrapPanel>


foreach(var ic in obj.Icons)
{
    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.StreamSource = new MemoryStream(ic.image);
    bi.EndInit();

    Image im = new Image();
    im.Source = bi;
    wpIcons.Children.Add(im);
}

所以,它可以工作,但不能逐行。

如何逐行制作图标?

【问题讨论】:

  • 为什么不使用 Stackpanel 呢?你应该看看 MVVM 模式。在后面的代码中添加项目是远远不够的。
  • 一行一行是什么意思?是纵向还是横向?
  • “每行 5 个项目”要求的范围从简单(限制 WrapPanel 的宽度,将水平堆栈面板作为项目的垂直堆栈面板或只是一个纯 UniformGrid?)到 hard(创建自己的面板),具体取决于您想要实现的目标。在给定的代码中,您可以尝试限制im.Width,以便只有5 图像适合,然后6th 将被包装,但是如果调整窗口大小等会发生什么?

标签: c# wpf wrappanel


【解决方案1】:

如果您希望每行 5 个项目,您可以指定 Image 元素和 WrapPanel 的固定宽度:

<WrapPanel x:Name="wpIcons" Grid.Row="3"
            Grid.RowSpan="2"
            Grid.Column="4"
            Width="100">
</WrapPanel>

foreach (var ic in obj.Icons)
{
    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.StreamSource = new MemoryStream(ic.image);
    bi.EndInit();

    Image im = new Image();
    im.Width = 20; //<-- = 100 / 5
    im.Source = bi;
    wpIcons.Children.Add(im);
}

【讨论】:

    【解决方案2】:

    要控制单个项目的数量,我建议您使用 UniformGrid。 这是一个例子:

      <UniformGrid Columns="2" Rows="2" Name="uniformGrid1" >
                <Image Source="pic1.jpg"></Image>
                <Image Source="pic2.jpg"></Image>
                <Image Source="pic3.jpg"></Image>
                <Image Source="pic4.jpg"></Image>
      </UniformGrid> 
    

    在给定的示例中,图片将显示在 2 行和 2 列上(在您的情况下,您可以设置 Rows="5" 而不设置列)。您可以根据需要修改列和/或行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-19
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多