首页 > 解决方案 > WrapPanel WPF 中的 StackPanel

问题描述

在此处输入图像描述

目标是创建这样的布局。

我来自 iOS 开发和 WPF 开发的新手,所以我的想法是 StackViews 的 CollectionViews 以及来自 iOS 的 4 个多媒体元素,但我知道在 WPF 中的工作方式与在 iOS 中的工作方式大不相同。所以我将在 WPF 中使用 StackPanels 和 WrapPanels,如果我的解决方案是错误的,请给我一个更好的解决方案。

<Window x:Class="WPF_MultiViewer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_MultiViewer"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <WrapPanel>
            <StackPanel x:Name="MyStackPanel">
                <StackPanel Orientation="Horizontal">
                    <Button Height="100" Width="80">Button1</Button>
                    <Button Height="100" Width="80">Button2</Button>
                </StackPanel>

                <StackPanel Orientation="Horizontal">
                    <Button Height="100" Width="80">Button1</Button>
                    <Button Height="100" Width="80">Button2</Button>
                </StackPanel>
            </StackPanel>
        </WrapPanel>
    </Grid>
</Window>

结果是这个 在此处输入图像描述

我知道如果我将其硬编码并复制粘贴 12 次,它会起作用,但问题是我想创建一个模板,然后动态创建它,例如在一列中创建 12 次 4 堆栈面板。为了轻松控制和维护它,如何在 WPF 中实现这一点?

标签: c#.netwpf

解决方案


给你一个例子:

<ItemsControl x:Name="Stacks" Grid.Column="0" ItemsSource="{Binding example}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Whatever you want"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Eaxmple}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

推荐阅读