.net - 成对包装 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 等的一些选择行为。
解决方案
如果您只在网格或堆栈面板中包含两个控件(矩形和分隔符),这应该可以为您解决问题并防止它们分开:
<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>
推荐阅读
- google-sheets - 在给定 m/s 后缀的 Google 表格中计算时间
- jenkins - 当作业失败 N 次时触发下游 jenkins 作业
- regex - Mac 地址正则表达式过滤掉坏 Mac
- reactjs - 如何在 Visual Studio 代码中配置设置以便更漂亮地为 react.js 工作
- algorithm - 关于蝙蝠算法的论文有误吗?
- spring - 我的 Spring EventListener 是否可以等待 2 个事件进行?
- python - 'DataFrame' 对象没有属性 'Book'
- powerbi - DAX:月平均
- javascript - 将索引数组分配为对象值
- gradle - 如何使用 Kotlin 将导入的插件整合到 Gradle 中的自定义插件