【问题标题】:Wrap items in WrapPanel in pairs成对包装 WrapPanel 中的项目
【发布时间】:2021-07-03 04:56:13
【问题描述】:

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

Item 可以是 Box 或 Separator。

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

这在此处直观地说明:

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

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

实现将“Box & Separator”对包装在一起的包装行为的最简单方法是什么?我必须自己滚动 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 等的一些选择行为。

【问题讨论】:

  • 任何源代码?
  • 是的,添加了示例代码。

标签: .net wpf


【解决方案1】:

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

    <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>

【讨论】:

  • 是的,但是如果我将它们放在同一个 DataTemplate 中,它们就不能单独选择。我在问题中添加了示例代码以更好地描述情况:)
  • 创建一个包含框和分隔符的自定义控件,或者使用样式来完成
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多