You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XAML的Grid中添加红色方块列表?

解决方案

你可以在主Grid的第二行(Row=1)的两个列中,分别放置容器控件(比如WrapPanel或嵌套Grid)来承载红色方块,不需要复杂的嵌套结构。以下是修改后的代码示例:

<Window x:Class="MonitorComenzi.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:MonitorComenzi"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        
        <!-- 标题行 -->
        <TextBlock Grid.Row="0" Grid.Column="0" FontSize="30" TextAlignment="Center" FontWeight="Bold" Foreground="Black">Comenzi plasate</TextBlock>
        <TextBlock Grid.Row="0" Grid.Column="1" FontSize="30" TextAlignment="Center" FontWeight="Bold" Foreground="Green">Comenzi preparate</TextBlock>
        
        <!-- 左侧红色方块容器 -->
        <WrapPanel Grid.Row="1" Grid.Column="0" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top">
            <Rectangle Fill="Red" Width="80" Height="80" Margin="5"/>
            <Rectangle Fill="Red" Width="80" Height="80" Margin="5"/>
            <Rectangle Fill="Red" Width="80" Height="80" Margin="5"/>
            <Rectangle Fill="Red" Width="80" Height="80" Margin="5"/>
        </WrapPanel>
        
        <!-- 右侧红色方块容器 -->
        <WrapPanel Grid.Row="1" Grid.Column="1" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top">
            <Rectangle Fill="Red" Width="80" Height="80" Margin="5"/>
            <Rectangle Fill="Red" Width="80" Height="80" Margin="5"/>
        </WrapPanel>
        
    </Grid>
    
</Window>

补充说明:

  • WrapPanel适合方块数量不确定的场景,它会自动让方块换行排列;如果需要固定行列的布局,也可以用嵌套Grid,手动定义行和列的尺寸。
  • 如果红色方块需要根据数据动态生成,建议使用ItemsControl,并将其ItemsPanel设置为WrapPanel或Grid,这种方式更符合WPF的数据绑定思想。

内容的提问来源于stack exchange,提问作者Cosmin Popa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:01:21