首页 > 解决方案 > 成对包装 WrapPanel 中的项目

问题描述

我有一个 WPF ListBox,它使用 WrapPanel 作为其 ItemsPanel,其水平方向显示项目的 ObservableCollection。

Item 可以是 Box 或 Separator。

在集合中,一个 Box 后面总是跟着一个 Separator,即像这样:Box、Separator、Box、Separator、Box、Separator 等。

此处直观地说明了这一点:

在此处输入图像描述

用户可以调整 WrapPanel 的宽度 - 问题就来了:如果用户将宽度调整到某些“不幸”的位置,那么 WrapPanel 会以不希望的方式换行,例如:

在此处输入图像描述

我希望每个“盒子和分隔符”对总是包裹在一起,即像这样:

在此处输入图像描述

实现“盒子和分隔符”对包裹在一起的包裹行为的最简单方法是什么?我必须滚动自己的 WrapPanel 吗?

以下是示例类和 ViewModel:

public abstract class Item
{

}

public class Box : Item
{

}

public class Separator : Item
{

}

public class ViewModel
{
        public ObservableCollection<Item> Items { get; } = new ObservableCollection<Item>
        {
            new Box(),
            new Separator(),
            new Box(),
            new Separator(),
            new Box(),
            new Separator()
        };

}

以及绑定到 ViewModel 的示例 XAML:


<ListBox ItemsSource="{Binding Items}">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type model:Box}">
            <Rectangle Fill="Blue" Height="50" Width="50" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type model:Separator}">
            <Rectangle Fill="Green" Height="50" Width="10" />
        </DataTemplate>
    </ListBox.Resources>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

注意:我知道我可以将分隔符作为 Boxes 的 DataTemplate 的一部分在视觉上呈现。但是,如果可能的话,我希望将它们保留为单独的对象,因为它们具有 ContextMenus 等的一些选择行为。

标签: .netwpf

解决方案


如果您只在网格或堆栈面板中包含两个控件(矩形和分隔符),这应该可以为您解决问题并防止它们分开:

    <WrapPanel>
        <StackPanel Orientation="Horizontal">
            <Rectangle Fill="HotPink" Height="100" Width="100"/>
            <Separator Height="100" Width="10"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Rectangle Fill="HotPink" Height="100" Width="100"/>
            <Separator Height="100" Width="10"/>
        </StackPanel>
    </WrapPanel>

推荐阅读