简体   繁体   中英

Group items in WPF WrapPanel

Using a ListBox with a WrapPanel set as the ItemsPanel, I am trying to achieve what is illustrated in this image:

在此处输入图片说明

However, currently the WrapPanel wraps like this: 在此处输入图片说明

The underlying model looks like this:

public class ViewModel
{
    public ObservableCollection<IRectangle> Rectangles { get; set; };
}

public class GreenRectangle : IRectangle
{

}

public class BlueRectangle : IRectangle
{

}

public interface IRectangle
{

}

The XAML looks like this:

<ListBox ItemsSource="{Binding Rectangles}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type GreenRectangle}">
            <Border Background="Green" Height="100px" Width="100px" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type BlueRectangle}">
            <Border Background="Green" Height="100px" Width="20px" />
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

The application is built on: WPF, PRISM, C# 6.0, .NET 4.0 and the MVVM pattern.

Here are some additional requirements/information:

  • The width and height of the WrapPanel may change at runtime.
  • The width and height of the rectangles are fixed.
  • The underlying model guarantees that the items of the Rectangles collection always alternate, that the collection always starts with a GreenRectangle, and that every GreenRectangle is always followed by exactly one BlueRectangle.
  • The GreenRectangle and BlueRectangle must be separately selectable.

Is there any way I can achieve what is illustrated on the first image? Can I somehow tell the WrapPanel to always wrap after a BlueRectangle or after an even item index? Or somehow "group" or pair a GreenRectangle with a BlueRectangle? I have looked into using a CollectionView but it doesn't seem to solve what I'm trying to achieve.

Any ideas and suggestions are welcome.

To consistently achieve the affect you are looking for switch to a UniformGrid instead of an WrapPanel .

There you can set the amount of Rows and Columns

I found that multiple articles with similar issue are pointing to the same thing UniformGrid .

Specify the max number of columns for a WrapPanel in WPF

and Is there an alternative to a WPF WrapPanel that wraps after a certain number of items, not a height?

I didn't try then so I'm not sure if they work but since they are both resolved I assume the do work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM